簡體   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