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
objectis null or undefined, evaluate toundefined - Otherwise, will access the
valueproperty on the object
object!.value is TypeScript syntax, and will:
- Assert to the TypeScript compiler that
objectis neither null nor undefined - Unconditionally attempt to access the
valueproperty 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)
