type ReactText = string | number;
type ReactChild = ReactElement | ReactText;
interface ReactNodeArray extends Array<ReactNode> {}
type ReactFragment = {} | ReactNodeArray;
type ReactNode = ReactChild | ReactFragment | ReactPortal | boolean | null | undefined;
类组件的 render 成员函数会返回 ReactNode 类型的值,而且 PropsWithChildren 类型中指定的 children 类型也是 ReactNode。
const Comp: FunctionComponent = props => <div>{props.children}</div>
// children?: React.ReactNode
type PropsWithChildren<P> = P & {
children?: ReactNode;
}
虽然 React 的类型定义看起来写得很复杂,但它实际上等价于:
type ReactNode = {} | null | undefined;
由于 {}
是所有对象的原型,你可以把几乎任何类型赋值给 ReactNode,但绝大多数情况下应该对它进行更详细的类型声明。