Typescript: how to set the type of children in a React component?

Can I set the type of children in TypeScript?

For example, I have such Components

class UserProfile extends React.Component<{ id: number }, void>{ } class Thumbnail extends React.Component<{ children: UserProfile[] }, void>{ } class UsersList extends React.Component<void, void>{ public render() { return ( <div> <Thumbnail><UserProfile id={1} /></Thumbnail> <Thumbnail><UserProfile id={2} /></Thumbnail> </div> ) } } 

I want to determine which specific children are supported in the Thumbnail component to avoid this situation:

 class UsersList extends React.Component<void, void>{ public render() { return ( <div> <Thumbnail><UserProfile id={1} /></Thumbnail> <Thumbnail><UserProfile id={2} /></Thumbnail> <Thumbnail><span>Some plain text</span></Thumbnail> // This should be forbidden because Thumbnail component expects to have an array of UserProfile elements as it can handle them </div> ) } } 

This example does not work, but is there any way to do this?

+8
reactjs typescript react-jsx
source share
1 answer

to set the type of children in the React component?

Cannot narrow with type annotation (whole JSX.Element). Can be performed with introspection of runtime ( type property of each child).

+3
source share

All Articles