Null coalescing operator angular 2

What is the equivalent of null coalescing operator (??) in angular 2?

In C# we can perform this operation:

string str = name ?? FirstName ?? "First Name is null";
39355 次浏览

Coalescing is performed via || operator, i.e.

let str:string = name || FirstName || "name is null and FirstName is null";

You can also read this question for more details and explanations.

Maybe what you want achieve is this:

let str =
typeof (name) !== 'undefined' && name !== null ?
name : typeof (FirstName ) === 'undefined' || FirstName  === null ?
"First Name is null" : FirstName

In Typescript

Typescript introduced null coalescing with version 3.7, so if you're running on 3.7 or higher you can simply write:

const str = name ?? firstName ?? "Name and First Name are both null";
const x = foo?.bar.baz() ?? bizz();

See https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html#nullish-coalescing.

In the Angular Template

Since Angular 12 you can also use ?? in the template.