INeedYourHelp
INeedYourHelp

Reputation: 171

Object is possibly undefined

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?

Upvotes: 2

Views: 31204

Answers (5)

Vijeth Gowda
Vijeth Gowda

Reputation: 21

There is one more way to solve this

const add = (item: Person): number => {
  const newValue = item.value || ''
  return newValue  + 1`
}

Upvotes: 1

Vivek Kumar
Vivek Kumar

Reputation: 113

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.

Upvotes: 1

Mahamudul Hasan
Mahamudul Hasan

Reputation: 2823

Actually i prefer to use (??) Nullish coalescing Operator

const add = (item: Person): number => {
  return (item?.value ?? 0) + 1
}

you can see also

Upvotes: 2

tim
tim

Reputation: 181

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
}

Upvotes: 2

antpngl92
antpngl92

Reputation: 534

Since your value property is number | undefined TS complains about it.

Upvotes: 2

Related Questions