Reactjs 在Typescript中,是否有任何方法可以检查JSX.Element';s

Reactjs 在Typescript中,是否有任何方法可以检查JSX.Element';s,reactjs,typescript,jsx,Reactjs,Typescript,Jsx,考虑这个简单的例子: 图书馆客户: class ClientComponent extends React.Component<any,any> { render() { const myNestedElement = (<LibNestedComponent/>) return <LibComponent nested={myNestedElement}/> } } class ClientComponen

考虑这个简单的例子:

图书馆客户:

class ClientComponent extends React.Component<any,any> {
    render() {
        const myNestedElement = (<LibNestedComponent/>)
        return <LibComponent nested={myNestedElement}/> 
    }
}
class ClientComponent扩展了React。Component甚至说:

JSX结果类型。默认情况下,JSX表达式的结果类型为any。您可以通过指定
JSX.Element
接口。但是,无法检索类型信息 关于JSX的元素、属性或子元素 接口。这是一个黑盒子

有没有人有一个解决办法,可以在不太痛苦的情况下实现这种类型的类型检查


(这个例子故意显得微不足道,并不意味着是一个合理的用例。)

除了我的评论之外,我不知道是否有一种类型脚本方法来限制客户端组件可以传递的组件类型。但是有一种方法可以确定作为道具传递的组件的类型

您可以检查传递的组件的名称,并查看其类型

if (this.props.nested.type.name === 'LibNestedComponent') {
   console.log('A valid component is passed');
} else {
   console.log('Invalid component is passed');
}
其中
nested
是您在提供的示例中传递的组件

在下图中,您可以看到组件的名称


但同样,这将是一个运行时检测。

您可以使用对象检查
this.props.nested
的类型

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

Hardik回答的问题是,如果代码缩小,则
type.name
的值将更改,代码将失败。因此,您应该直接使用
type
属性。

我看到了一些关于基于类型的方法来限制父/子组件的问题,但据我所知,没有。对于任何元素,您都可以将类型指定为
React.ReactElement
,这会将传入的嵌套属性限制为
LibComponentProps
@HardikModha中的一个,我不确定您打算如何使用
ReactElement
,但这可能是不正确的、未强制的或不正确的。您能说明您的意思吗?从的类型定义中,您可以看到
JSX.Element
扩展了接口
ReactElement
。因此,您可以使用
React.ReactElement

而不是
JSX.Element
。由于可以将类型接口作为泛型参数传递,因此它将限制prop为您提供的类型之一。但仍然不确定这是您想要的。@HardikModha,它不约束元素的类型,只约束元素的参数。不过,总比没有强!我错误地认为它没有被强制执行,但在一个道具界面中发现了一个
[name:string]:any
,它为任何东西打开了谷仓的门。谢谢谢谢不过,我正试图找到编译时验证!
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')
}