TypeScript recursive types

0 views
Skip to first unread message

Mike Austin

unread,
Nov 26, 2025, 8:09:40 PM (6 days ago) Nov 26
to PiLuD
Obvious when creating "Tree" type for example, but also useful when you want to type React children. ReactNode lets everything in, which is sometimes useful, but if you need to clone an element, setting a specific prop, TypeScript needs to know about it.

type Children = false | React.ReactElement<{ style: React.CSSProperties }> | Children[];

function Stack({
  children
}: {
  children: Children;
}) {
  ... cloneElement(child, { style: ... })
}

boolean is needed because children can have "array.length !== 0 && ...", or "array.map()" can return multiple element, which are eventually flattened.

type ReactNode =
  | ReactElement
  | string
  | number
  | Iterable<ReactNode>
  | ReactPortal
  | boolean
  | null
  | undefined;

Reply all
Reply to author
Forward
0 new messages