Home > database >  What is difference between myvariable.subproperty?.value and myvariable.subproperty!.value?
What is difference between myvariable.subproperty?.value and myvariable.subproperty!.value?

Time:01-06

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!

CodePudding user response:

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)

  •  Tags:  
  • Related