かもメモ

自分の落ちた落とし穴に何度も落ちる人のメモ帳

React TypeScript children の型のメモ

React の children の型がコードレビューの時に { children: JSX.Element | null } って書かれてて、自分は ReactNode って書くことが多かったのでどっちが良いんだろう?と自信なかったのでググったのメモ書き

結論: children の型は React.ReactNode で良さそう

React.ReactNodeJSX.Element を内包していて、JSX.Element 単体よりカバーできる範囲が広いので React の children の型は React.ReactNode にしておけば良さそう。

ReactNode, JSX.Element の型を見てみる

  • react 17.0.2

React.ReactNode の型

type ReactNode = ReactChild | ReactFragment | ReactPortal | boolean | null | undefined;

type ReactFragment = {} | Iterable<ReactNode>;

type ReactChild = ReactElement | ReactText;
  interface ReactElement<P = any, T extends string | JSXElementConstructor<any> = string | JSXElementConstructor<any>> {
    type: T;
    props: P;
    key: Key | null;
  }
  type ReactText = string | number;

interface ReactPortal extends ReactElement {
  key: Key | null;
  children: ReactNode;
}

JSX.Element の型

declare global {
  namespace JSX {
    interface Element extends React.ReactElement<any, any> { }
    // ...

JSX.Element is a ReactElement, with the generic type for props and type being any. It exists, as various libraries can implement JSX in their own way, therefore JSX is a global namespace that then gets set by the library,

<p> // <- ReactElement = JSX.Element
   <Custom> // <- ReactElement = JSX.Element
     {true && "test"} // <- ReactNode
  </Custom>
 </p>
cf. javascript - When to use JSX.Element vs ReactNode vs ReactElement? - Stack Overflow

JSX.Element = ReactElement ということらしい。 ReactElementReactChild 型に内包されていて、ReactChildReactNode 型に含まれている。
JSX.Element ⊂ React.ReactNode になっているっぽい

📝 <Container> で囲って children で渡した方がパフォーマンス良くなるらしい


[参考]

タイトルだけ知ってたけど、1巻と60巻とで表紙のデザインかなり変わってるようなシリーズもあるんですね