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

With the following code:

var x:boolean = true;

x &= false;

Results in error TS2447: The '&=' operator is not allowed for boolean types. Consider using '&&' instead.

I've looked around but can't find a reason why, there's a PR to make the error what it is: https://github.com/Microsoft/TypeScript/issues/712 but still can't find the underlying reason for it.

Can someone clarify?



Solution 1:[1]

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.

Solution 2:[2]

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

Solution 3:[3]

My issue was that I was doing

x |= y

instead of what I meant, which is

x ||= y

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 NearHuscarl
Solution 3 Boris Verkhovskiy