Objects are not valid renderable children in React, and trying will throw an invariant violation. This happens most commonly in my projects when we accidentally rendering an Error object (instead of error.message
). Typescript knows that Error doesn't conform to the ReactNode type, yet it does not warn when I haphazardly pass this object as a child to JSX IntrinsticElements (as in <b>{error}</b>
) or otherwise return it from render.
Is it possible to get Typescript to check the types of rendered objects, so that they extend ReactNode and therefore can be successfully rendered?
For clarity, this is @types/react
's related type definitions:
type ReactText = string | number;
type ReactChild = ReactElement | ReactText;
interface ReactNodeArray extends Array<ReactNode> {}
type ReactFragment = {} | ReactNodeArray;
type ReactNode = ReactChild | ReactFragment | ReactPortal | boolean | null | undefined;
Related question, not typescript: Invariant Violation: Objects are not valid as a React child