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

Viewed 9921

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?

3 Answers

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

My issue was that I was doing

x |= y

instead of what I meant, which is

x ||= y
Related