我可以在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>
)
}
}
这个例子不起作用,但是有什么方法可以做到吗?
答案 0 :(得分:3)
在React Component中设置子类型?
不能使用类型注释(它的所有JSX.Element)缩小范围。可以使用运行时内省(每个子项的test_input <- structure(list(ID = c(1L, 1L, 1L, 1L, 2L,
2L), Category = c("X",
"X", "X", "X", "X", "X"), ItemId_na = c(2L, 2L, 2L, 2L,
3L, 3L
), Item.Type1_na = c(1L, 2L, 3L, 4L, 1L, 2L)),
.Names = c("ID",
"Category", "ItemId_na", "Item.Type1_na"),
row.names = c(NA, 6L), class = "data.frame")
属性)来完成。