我可以在TypeScript中设置子类型吗?
例如,我有这样的组件
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> ) } }
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> ) } }
这个例子不起作用,但是有什么方法可以做到吗?
set type of children in React Component?
不能用类型注释缩小(它的所有JSX.Element).可以使用运行时内省(每个子项的type属性)来完成.