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[]'.
CodePudding user response:
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
)