简体   繁体   English

类型错误:类型上不存在属性

[英]TypeError : Property does not exist on type

I am using a type script for the react project.我正在为 React 项目使用类型脚本。 I have defined the type for all values, but prop.option?I can't get the value of the name.我已经定义了所有值的类型,但是prop.option?我无法获取名称的值。 Please tell me the answer.请告诉我答案。

type PropTypes = {
  option?: OptionType[]
}

type OptionType = {
  id?: number
  name?: string
  price: number
  quantity: number
}

function OrderItemPCForm(props: PropTypes) {

  console.log('===>', props.option?.name)
return(<div>...</div>)}
Property 'name' does not exist on type 'OptionType[]'.

Your problem was you defined option as an array (not an object)您的问题是您将option定义为数组(不是对象)

option?: OptionType[]

so that when you try to access values from这样当您尝试访问值时

console.log('===>', props.option?.name)

It will throw an error because you try to get name from option object which is not defined它会抛出错误,因为您尝试从未定义的option object 中获取name

It has 2 ways to fix它有两种修复方法

The first one is you should remove an array definition on option第一个是您应该删除option上的数组定义

type PropTypes = {
  option?: OptionType //removed `[]`
}

The second fix can be第二个修复可以是

console.log('===>', props.option[index].name) //index can be populated from a loop

But it also depends on your intention which type you want to achieve (an array or an object on option )但这也取决于您想要实现哪种类型的意图(一个数组或一个 object option

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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