Videos
! is non-null assertion operator (post-fix expression) - it just saying to type checker that you're sure that a is not null or undefined.
the operation
a!produces a value of the type ofawithnullandundefinedexcluded
Optional chaining finally made it to typescript (3.7)
The optional chaining operator
?.permits reading the value of a property located deep within a chain of connected objects without having to expressly validate that each reference in the chain is valid. The?.operator functions similarly to the.chaining operator, except that instead of causing an error if a reference is nullish (nullorundefined), the expression short-circuits with a return value ofundefined. When used with function calls, it returnsundefinedif the given function does not exist.
Syntax:
obj?.prop // Accessing object's property
obj?.[expr] // Optional chaining with expressions
arr?.[index] // Array item access with optional chaining
func?.(args) // Optional chaining with function calls
Pay attention:
Optional chaining is not valid on the left-hand side of an assignment
const object = {};
object?.property = 1; // Uncaught SyntaxError: Invalid left-hand side in assignment
Since TypeScript 3.7 was released you can use optional chaining now.
Property example:
let x = foo?.bar.baz();
This is equvalent to:
let x = (foo === null || foo === undefined)
? undefined
: foo.bar.baz();
Moreover you can call:
Optional Call
function(otherFn: (par: string) => void) {
otherFn?.("some value");
}
otherFn will be called only if otherFn won't be equal to null or undefined
Usage optional chaining in IF statement
This:
if (someObj && someObj.someProperty) {
// ...
}
can be replaced now with this
if (someObj?.someProperty) {
// ...
}
Ref: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html