[英]TypeScript "TS2339: Property 'X' does not exist on type 'Y'" error even though type is defined
在我的代码中,我试图访问React.ReactElement
数组元素的type
属性。 即使我已经定义了包含React.ReactElement
子元素的数组,我在尝试访问数组元素的type
属性时React.ReactElement
出错,除非我将数组元素React.ReactElement
类型。
这是我的代码:
const getChildren = (
children: (React.ReactChild | React.ReactElement)[]
) => {
console.log((children[0] as React.ReactElement).type) // this line works
console.log(children[0].type) // this line breaks
}
这是我得到的错误:
Property 'type' does not exist on type 'ReactChild | ReactElement<any, string | JSXElementConstructor<any>>'.
Property 'type' does not exist on type 'string'. TS2339
我该如何解决这个问题?
我不熟悉 React,但我假设React.ReactChild
没有名为type
属性,这就是您收到错误的原因。
Typescript 编译器不知道您的项目是React.ReactElement
类型( React.ReactChild
或React.ReactElement
),除非您明确告诉编译器是哪种类型。 这就是函数中的第一行起作用的原因,因为您明确告诉编译器在函数中传递的参数是React.ReactElement[]
或至少数组中的第一个元素是React.ReactElement
类型的参数。
如果您知道数组中的元素将始终是React.ReactElement
的类型,那么我建议您将函数参数类型更改为
const getChildren = (children: React.ReactElement[]) => {/* ... */}
否则你应该检查它是哪种类型以避免运行时错误:
const getChildren = (children: (React.ReactChild | React.ReactElement)[]) => {
if (children[0] instanceof React.ReactChild) {
console.log(children[0].type);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.