繁体   English   中英

打字稿“TS2339:属性 'X' 不存在于类型 'Y'”错误,即使类型已定义

[英]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.ReactChildReact.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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM