Does TypeScript have a Null-conditional operator

Viewed 23874

Is there any operator like ?. in TypeScript that can check if the variable is null or not defined like Kotlin? Like

person?.getName()?.firstName ?: "None"
8 Answers

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 used this in my code to check for null

this.firstname = (this.firstname != null) ? this.firstname : this.firstname;

This could do till v3 is out

Not only is it supported in typescript (since version 3.7.2). It is also supported in javascript now (since ES2020).

  • In practice that means you can use it in frameworks like Angular (since v9 which supports typescript 3.7).

  • But especially now that it is in the ES2020 spec, we will be seeing it everywhere.

This will set item to null if there is no e-mail:

let item = user?.email;
Related