LoginSignup
0
0

More than 1 year has passed since last update.

React 関数コンポーネントのお型付け

Last updated at Posted at 2022-11-15

React には React.FC という型が存在します。
それを使えば大抵の関数コンポーネントに型注釈を書くことができるのですが、それに頼りたくない場合もあると思います(ジェネリクスを使いたい場合など)。
では、その場合はどうすれば良いのでしょうか。

React.FC の型定義1

    type FC<P = {}> = FunctionComponent<P>;

    interface FunctionComponent<P = {}> {
        (props: P, context?: any): ReactElement<any, any> | null;
        propTypes?: WeakValidationMap<P> | undefined;
        contextTypes?: ValidationMap<any> | undefined;
        defaultProps?: Partial<P> | undefined;
        displayName?: string | undefined;
    }

となっています。
ところで JSX.Element という型があるのですが、こちらは

        interface Element extends React.ReactElement<any, any> { }

となっています。
よって、関数コンポーネントの型注釈は以下で良いことになります。

const MyComponent = (props: Props): JSX.Element => {
  return <p>hello!</p>;
};

ちなみに React 公式ドキュメントである How to Upgrade to React 18 曰く、children の型は以下で良いようです。

interface Props {
  children?: React.ReactNode
}

React.PropsWithChildren という型があるのですが、そこからも children は React.ReactNode で良いことが伺えます。

    type PropsWithChildren<P = unknown> = P & { children?: ReactNode | undefined };
  1. 本記事で参照している型は @types/react v18.0.21 のものです。

0
0
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
0
0