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

隐身守侯 提交于 2020-01-02 01:09:29

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/36085104/typescript-how-to-set-type-of-children-in-react-component

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!