0
setTimeoutの型注釈とReactでの実装例
2022-08-01

よく考えずに実装するとこんな感じで怒られる

  Type 'Timeout' is not assignable to type '(prevState: number | undefined) => number | undefined'.
    Type 'Timeout' provides no match for the signature '(prevState: number | undefined): number | undefined'.
  • 参考というか答え

TypeScript - use correct version of setTimeout (node vs window) - Stack Overflow

次のようにして解決する

const timerId = useRef<ReturnType<typeof setTimeout>>();

if (timerId.current) {
  clearTimeout(timerId.current);
}

timerId.current = setTimeout(() => search(query), 1000);

ReturnType<typeof ...>はよく使えるパターンだと思うので覚えておく

ReactだとuseStateを使ってtimerIdを管理するかと思ったがuseStateだとうまく想定通りの挙動をしてくれなかったためuseRefで実装した

下記の実装を参考にした

react-use/useTimeoutFn.ts at master · streamich/react-use

場合によってはそのまま上記のuseTimeoutFnを使うのもあり

0

Profile

swfz
swfz
日々学んだことを残していく
Today I Learned
コード片置き場

Account

RSS

Powered by Pixela
© 2024. swfz