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?
addreturn? The compiler is telling you about a legitimate problem - that property might be undefined, according to the type information you've given it, in which case your function returnsNaN.