简体   繁体   中英

TypeError : Property does not exist on type

I am using a type script for the react project. I have defined the type for all values, but prop.option?I can't get the value of the name. 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?: 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

It has 2 ways to fix

The first one is you should remove an array definition on 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 )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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