[英]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.