Can i set 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 define what particular children are supported in Thumbnail component in order to avoid such 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 doesn't work, but is there any way to do it?
You have correctly set the children props for a custom component in React javascript but with typescript doing the same raises errors. To set the children props for a component in typescript you would have to take into account the type of the children and in this case, it is of type JSX.Element.
The React children prop is an important concept for creating reusable components because it allows components to be constructed together. However, a common issue with using React with Typescript is figuring out which data type to use with React children since Typescript is a strongly typed library.
To type check the child, use React.ReactElement type, along with the type for the child's props. In this case, it is UserInterface. TypeScript is an excellent utility that can be used to create a type-checked codebase.
Iterating through a component's children is the same as any other array. Use the map method in this case as well. To type check the child, use React.ReactElement type, along with the type for the child's props. In this case, it is UserInterface.
set type of children in React Component?
Can't be narrowed with a type annotation (its all JSX.Element). Can be done with runtime introspection (type
property of each child).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With