[英]TypeScript "TS2339: Property 'X' does not exist on type 'Y'" error even though type is defined
In my code, I'm trying to access the type
property of a React.ReactElement
array element.在我的代码中,我试图访问React.ReactElement
数组元素的type
属性。 Even though I've defined the array to contain React.ReactElement
children, I get an error trying to access an array element's type
property unless I cast the array element to be of the type React.ReactElement
.即使我已经定义了包含React.ReactElement
子元素的数组,我在尝试访问数组元素的type
属性时React.ReactElement
出错,除非我将数组元素React.ReactElement
类型。
Here's my code:这是我的代码:
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
}
and here's the error that I get:这是我得到的错误:
Property 'type' does not exist on type 'ReactChild | ReactElement<any, string | JSXElementConstructor<any>>'.
Property 'type' does not exist on type 'string'. TS2339
How can I resolve this issue?我该如何解决这个问题?
I'm not familiar with React but I'm assuming that React.ReactChild
has no attribute named type
and this is the reason you are getting the error.我不熟悉 React,但我假设React.ReactChild
没有名为type
属性,这就是您收到错误的原因。
Typescript compiler has no idea of knowing which of the types ( React.ReactChild
or React.ReactElement
) your item is unless you explicitly tell the compiler which one is it. Typescript 编译器不知道您的项目是React.ReactElement
类型( React.ReactChild
或React.ReactElement
),除非您明确告诉编译器是哪种类型。 This is why your first line in the function works, because you explicitly tell the compiler that the argument passed in the function is React.ReactElement[]
or at least the first element in the array is the argument of type React.ReactElement
.这就是函数中的第一行起作用的原因,因为您明确告诉编译器在函数中传递的参数是React.ReactElement[]
或至少数组中的第一个元素是React.ReactElement
类型的参数。
If you know that elements in an array will always be a type of React.ReactElement
then I suggest you to change the function argument type to be如果您知道数组中的元素将始终是React.ReactElement
的类型,那么我建议您将函数参数类型更改为
const getChildren = (children: React.ReactElement[]) => {/* ... */}
otherwise you should check it which of the types is it to avoid runtime errors:否则你应该检查它是哪种类型以避免运行时错误:
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.