How Children Types Work In React 18 And TypeScript 4

PHOTO EMBED

Sat Jan 07 2023 03:24:48 GMT+0000 (Coordinated Universal Time)

Saved by @ocnarb

type ChildProps = {
  vegetables: string[]  
}

function MyComponent({ children }: { 
  children: React.ReactElement<ChildProps>
}) {
  React.Children.forEach(children, (child) => {
    console.log(child.props.vegetables) // no error!
    console.log(child.props.fruit)
    // error! Property 'fruit' does not exist on type 'ChildProps'
  })
}
content_copyCOPY

https://www.arahansen.com/how-children-types-work-in-react-18-and-typescript-4/