打字稿:如何在 React Component 中设置 children 的类型?

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

我可以在 TypeScript 中设置 children 的类型吗?

例如我有这样的组件

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

我想定义缩略图组件支持哪些特定的 children 以避免出现这种情况:

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)。可以通过运行时自省来完成(每个 child 的 type 属性)。