I have following type:
type Person = {
name: string
age: number
value?: number
}
Also I have mock array of objects:
const arr = [
{
name: 'A',
age: 1
},
{
name: 'B',
age: 2
}
]
Now I would like to add to each object in array property value
const newArr = arr.map(item => {
return {
...item,
value: fun(item)
}
})
And here is a function which add value
const add = (item: Person): number => {
return item.value 1
}
Now we have a TypeScript problem:
Object is possibly 'undefined'.ts(2532)
I am pretty sure that I can't do something like that because I need to return number?
const add = (item: Person): number => {
return item.value && item.value 1
}
How should I handle this?
CodePudding user response:
Because you defined value to be optional, your add function cannot be sure that it exists. Therefore, its behaviour is not well-defined. What should it return if an item is passed which has no value attribute?
You can either make value be a required attribute / create a new interface:
interface ValuedPerson extends Person {
value: number;
}
const add = (item: ValuedPerson): number => {
return item.value 1
}
or add a default value, as this answer suggests.
After OP's remark: You can tell TypeScript that it does exist by adding an exclamation mark:
const add = (item: Person): number => {
return item!.value 1
}
CodePudding user response:
Typescript is yelling at you because you are still not returning a number.
const add = (item: Person): number => {
return item.value && item.value 1
}
This will return a number if value is present in item, if not, it will return undefined.
EITHER
Make value a required attribute.
OR
Do a ternary check.
const add = (item: Person): number => {
return item.value ? item.value 1 : 0
}
I am assuming, you want to add 0 to value if value is not present.
Typescript should now be happy.
CodePudding user response:
Since your value property is number | undefined TS complains about it.
CodePudding user response:
Actually i prefer to use (??) Nullish coalescing Operator
const add = (item: Person): number => {
return (item?.value ?? 0) 1
}
