Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript: how to set type of children in React Component?

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?

like image 319
aspirisen Avatar asked Mar 18 '16 13:03

aspirisen


People also ask

How to set children props for a React component in typescript?

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.

Is it possible to use react with typescript?

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.

How to type check the child component in react?

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.

How to iterate through a component's children in react?

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.


1 Answers

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).

like image 170
basarat Avatar answered Sep 22 '22 10:09

basarat