Does Typescript currently (or are there plans to) support the safe navigation operator of
var thing = foo?.bar // same as: var thing = (foo) ? foo.bar : null;
Also, is there a more common name for this operator (it’s incedibly hard to google for).
Yes. As of TypeScript 3.7 (released on November 5, 2019), this feature is supported and is called Optional Chaining:
At its core, optional chaining lets us write code where TypeScript can immediately stop running some expressions if we run into a
undefined. The star of the show in optional chaining is the new
?.operator for optional property accesses.
Refer to the TypeScript 3.7 release notes for more details.
Prior to version 3.7, this was not supported in TypeScript, although it was requested as early as Issue #16 on the TypeScript repo (dating back to 2014).
- CoffeeScript refers to it as the existential operator (specifically, the "accessor variant" of the existential operator):
The accessor variant of the existential operator
?.can be used to soak up null references in a chain of properties. Use it instead of the dot accessor
.in cases where the base value may be null or undefined.
- C# calls this a null-conditional operator.
a null-conditional operator applies a member access,
?., or element access,
?, operation to its operand only if that operand evaluates to non-null; otherwise, it returns
- Kotlin refers to it as the safe call operator.
There are probably lots of other examples, too.
Answered By – Donut
Answer Checked By – David Goodson (BugsFixing Volunteer)