考虑这个简单的案例:
图书馆客户:
class ClientComponent extends React.Component<any,any> {
render() {
const myNestedElement = (<LibNestedComponent/>)
return <LibComponent nested={myNestedElement}/>
}
}
库:
class LibNestedComponent extends React.Component<any,any> {
render() { return <div>nested stuff</div> }
}
interface LibComponentProps { nested: JSX.Element }
class LibComponent extends React.Component<LibComponentProps,any> {
render() {
return <div>{this.props.nested}</div>
}
}
作为Lib的作者,我希望能够通过LibComponent
界面告诉我的LibComponentProps
客户,传入的nested
道具必须是一个元素类型LibNestedComponent
- 不仅仅是任何旧的j.random元素。但是AFAICT,没有办法做到这一点; Typescript doc甚至说:
JSX结果类型。默认情况下,JSX表达式的结果输入为any。您可以通过指定
JSX.Element
来自定义类型 接口。但是,无法检索类型信息 关于JSX的元素,属性或子元素 接口。这是一个黑盒子。
有没有人有一种解决方法可以在没有太多痛苦的情况下实现这种类型的检查?
(这个例子故意是微不足道的,并不意味着是一个明智的用例。)
答案 0 :(得分:1)
除了我的评论之外,我不知道是否有一种打字机方式来限制客户端组件可以传递的组件类型。但是有一种方法可以确定作为道具传递的组件类型。
您可以检查传递的组件的名称,并查看它的类型。
if (this.props.nested.type.name === 'LibNestedComponent') {
console.log('A valid component is passed');
} else {
console.log('Invalid component is passed');
}
其中nested
是您在提供的示例中传递的组件。
在下图中,您可以看到组件的名称。
但同样,这将是一次运行时检测。
答案 1 :(得分:1)
您可以使用对象
检查 R C L S V
1 4 5 na na na
2 na 5 5 5 na
...
的类型
this.props.nested
Hardik的答案是,如果您的代码缩小,if (this.props.nested.type !== LibNestedComponent) {
throw new Error('Invalid prop passed. Make sure that an instance of LibNestedComponent is passed through the nested prop')
}
的值将会更改,您的代码将失败。所以你应该直接去type.name
属性。