What is difference between myvariable.subproperty?.value and myvariable.subproperty!.value?

0

Issue

What is the difference between: myvariable.subproperty?.value and myvariable.subproperty!.value
It seems both execute if subproperty is null, delivering a null value. I know what assertion operators mean in general, just not sure what it means when you chain call properties like this.
Thanks!

Solution

object?.value is JavaScript syntax, and will:

  • If object is null or undefined, evaluate to undefined
  • Otherwise, will access the value property on the object

object!.value is TypeScript syntax, and will:

  • Assert to the TypeScript compiler that object is neither null nor undefined
  • Unconditionally attempt to access the value property on the object

If there’s a chance that the object is null or undefined, ?. is the right approach, because if you use !, a runtime error could result. (Only use ! when you’re absolutely certain that the expression on the left will always exist, and you need to indicate that to the TypeScript compiler)

Answered By – CertainPerformance

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More