繁体   English   中英

如何使用 TypeScript 在 useRef 挂钩中键入函数

[英]How to type functions in useRef hook with TypeScript

我有一个组件:

interface MyRef {
  foo: () => Promise<string>;
  bar: () => Promise<string>;
}

const Component: React.FunctionComponent = () => {
  const myRef = useRef<MyRef>({
    foo: async () => 'foo',
    bar: async () => myRef.current.foo(),
  });

  return <p>Comp</p>;
};

TypeScript 抱怨'myRef' implicitly has type 'any' because it does not have a type annotation and is referenced directly or indirectly in its own initializer.ts(7022)

我应该怎么做才能让 TypeScript 知道myRef.current.foo()的类型?

您可以按如下方式设置myRef的类型。

const myRef: MutableRefObject<MyRef> = useRef<MyRef>({
    foo: async () => "foo",
    bar: async () => myRef.current.foo()
  });

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM