Logical assignment operators in Typescript

Hi there, Tom here! As of writing, Typescript 4's stable release is imminent (August 2020) and with it are some very nice changes to come.

Typescript 4 ahead

One of those is the addition of logical assignment operators, which allow to use the logical operators with an assignment. As a reminder, here are the logical operators being used for the new logical assignment operators:

  • &&
  • ||
  • ??

These new logical assignment operators themselves are part of the collection of compound assignment operators, which apply an operator to two arguments and then assign the result to the left side. They are available in many languages and now get enhanced in Typescript.

Code, please!

What does that mean? You probably already know a few compound assignment operators:

// Addition, Subtraction, Multiplication, Division
x += y;
x -= y;
x *= y;
x /= y;

The new logical assignment operators now give you the ability to use your logical operator of choice for the same kind of assignment:

// Replacing x && (x = y)
x &&= y;

// Replacing x || (x = y)
x ||= y;

// Replacing x ?? (x = y)
x ??= y;

// And here's an exmple from the Typescript-team:
let values: string[];

// Before
(values ?? (values = [])).push("hello");

// After
(values ??= []).push("hello");

Note that these new operators were already available in JS and are also natively suppported by V8.

And that’s about it for one of Typescript 4’s great new features. Thanks for the quick read and I hope you could learn something!

- Tom


expressFlow is now Lean-Forge