Why are logical assignment (&=) operators disallowed in Typescript?

Typescript 4.0+ now supports logical assignment. Here is the online example.

type Bool = boolean | null | undefined;

let x: Bool = true;

x &&= false; // => false
x &&= null; // => null
x &&= undefined; // => undefined

let y: Bool = false;

y &&= true; // => false
y &&= null; // => false
y &&= undefined; // => false

Which is equivalent to

type Bool = boolean | null | undefined;

let x: Bool = true;

x && x = false; // => false
x && x = null; // => null
x && x = undefined; // => undefined

let y: Bool = false;

y && y = true; // => false
y && y = null; // => false
y && y = undefined; // => false

I can't speak on behalf of the designers of TypeScript but the & (bitwise AND) operator is intended to perform the a bitwise AND operation on two integers. Your variable is a boolean and these values are combined using && (logical AND).

In TypeScript you could conceivably create an &&= operator but the && operator uses short-circuit evaluation where evaluation stops as soon the result is known which means that the semantic of x &&= y becomes a bit clouded.

Tags:

Typescript