3
interface c {
    state?: {b: string}
}

const x: c = { state: {b: 'c'}}
console.log(x.state.b)

In the above code, In interface c, state is an optional property.

However when I want to access the property b of the state object whenever it is set, it is giving me this error, Object is possibly 'undefined'. What is the right way to fix this?

Kishan Rajdev
  • 1,919
  • 3
  • 18
  • 24

2 Answers2

7

That's because state can be undefined, and the compiler doesn't always know when it is definitely defined.

You can tell it you're sure it's defined, just use:x.state!.b

zmbq
  • 38,013
  • 14
  • 101
  • 171
2

If you are sure that an optional(field marked with ?) has a value, this can be achieved by checking it for a value:

if(x.state !== undefined){
  console.log(x.state.b)
}

you can use a ! to mark it as present:

console.log(x.state!.b)
MaartenDev
  • 5,631
  • 5
  • 21
  • 33