LoginSignup
9
3

More than 1 year has passed since last update.

【React】頑張って全部の型を書かないで

Last updated at Posted at 2022-12-11

はじめに

世の中がTypeScriptファーストになってきたので、React×TypeScriptで開発しているチームも多いと思います。

Reactには型を全部自分で書かなくていいようにUtil Typesを作ってくれてます。

今回はよく使うやつを紹介していきます

子コンポーネントのProps

子コンポーネントのPropsを入手したいとき、親に同じpropsを書いたり、子コンポーネントのtypeをexportしたりするコードをちょくちょくみます。

こんな時に使うのが、ComponentPropsWithoutRef(refを必要とする場合はComponentPropsWithRef)。

import { ComponentPropsWithoutRef } from "react";
import { Name } from "./Name";

type Props = {
  name: ComponentPropsWithoutRef<typeof Name>;
};

めちゃくちゃ簡単に子コンポーネントのPropsの型を入手できます。
簡単というのもそうですが、子コンポーネントのPropsが変わった時に親は変えなくて良いというのがいいですね。

children

コンポーネントがchildrenを受け取りたいことがあるかと思います。
React v17までは、FC(Functional Component)という型にchildrenが暗黙的に含まれるという仕様でしたが、React v18からは削除されたので、明示的にchildrenを受け取るかどうかを書く必要があります。

この時

import { ReactNode } from "react";

type Props = {
  children: ReactNode;
};

としてしまうパターンをよくみます。
こちらもReactがPropsWithChildrenという型を用意してくれているので使うのが良いと思います。

import { PropsWithChildren } from "react";

type Props = PropsWithChildren<{ name: string }>;

export const Profile: FC<Props> = ({ name, children }) => {

}

まとめ

今回はReact×TypeScriptでよく使う型について紹介しました。
型周りもよく修正が入るので、常にチェックが必要ですね。(地味に書き換えるの大変なんですよね、、汗

9
3
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
9
3