Does TypeScript have a Null-conditional operator
Yes, as of Typescript 3.7 you can now do this via optional-chaining
person?.getName()?.firstName
gets transpiled to
let firstName = person === null || person === void 0 ? void 0 : (_person$getName = person.getName()) === null || _person$getName === void 0 ? void 0 : _person$getName.firstName;
Note the check for null. This will work as expected if for example person is defined as
let person:any = null; //no runtime TypeError when calling person?.getName()
However if person is defined as
let person:any = {};//Uncaught TypeError: person.getName is not a function
See also this similar stackoverflow question
I've encountered the same situation, and the following worked for me.
First, I defined a separate class with a property that can be null
:
export class Foo {
id: number; //this can be null
}
Then in my main class I set a property foo
to this new type:
foo: Foo
After that, I was able to use it like this:
var fooId = (this.foo || ({} as Foo)).id;
This is the closest I could get to have a null propagation in a current version of TypeScript.
No, as of now safe navigation operatior is still not implemented in Typescript: https://github.com/Microsoft/TypeScript/issues/16
However according to the latest standardization meeting notes it has been proposed, so maybe v3 :)
https://github.com/tc39/agendas/blob/master/2017/07.md