1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Reactのカスタムフックを定義する時には型に注意!

Posted at

最初から結論

カスタムフック自体に型をつけてなかったから、定義したカスタムフックを別のコンポーネントでimportした時に型関連のエラーが出てた

-> カスタムフック自体に戻り値の型をつければ万事解決!!

// この部分
type funcs = {
  setTimer: () => void;
  resetTimer: () => void;
};
type Timer = [number, funcs];

export const useTimer = (): Timer => {
  const [time, setTime] = useState<number>(0);
  const setTimer = (): void => {};
  const resetTimer = (): void => {};
  // (中略)
  return [ time, { setTimer, resetTimer } ];
}

まとめ

考えてみれば当然って感じですね。
コンポーネント・関数の型定義は、暗黙的な型変換に頼ることが多かったので気付くのが遅れちゃいました…

もし、僕と同じく暗黙的な型変換をよく使う人がいたらこんなエラーがあったことを頭の片隅に入れてもらえたら幸いです。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?