Derek Lawless

There is always sunshine. Far above the grey sky

31st January 2020

Null coalescing in TypeScript

2 min read

The null coalescing operator has been a long requested feature in TypeScript. Indeed, when I began using TypeScript a few years ago, I assumed it was available and was suprised to find this wasn't the case.

Null coalescing remained unsupported until recently because the TypeScript team (rightly) wanted to mantain compatibility with any eventual TC39 decisions regarding implementation and semantics.

Given the ECMAScript proposal is now at stage 4, the TypeScript team have responded by adding support for the ?? operator in TypeScript version 3.7.

The null coalescing operator is useful when you want to use a 'default' value in an expression. In TypeScript and JavaScript you will find the following pattern regularly used:

const a = b || c;

While this appears to achieve the same end (and in many cases, will) the logical OR operator (||) applies for any falsy value i.e. null, undefined, "", 0, NaN, false:

const b = 0;
const c = 42;
const a = b || c;

console.log(a); // 42

The null coalescing operator (??) is more strict; it only applies where the value is null or undefined:

const b = 0;
const c = 42;
const a = b ?? c;

console.log(a); // 0

This additional strictness can be useful in scenarios where subtle errors may otherwise be introduced due to unintended falsy evaluation i.e. where 0, NaN, or "" are valid values in your application data or state.