Caleb Taylor
Caleb Taylor

Reputation: 3230

Typescript typeguard boolean results in never

I have a variable topLeft that's a boolean and it can have types of either number or boolean. topLeft will changed into a number and if it's already a number then increase it by one. I have a typeguard that turns topLeft into a number if it was a boolean. But in the else statement, the variable results in never type.

type BoxCell = number | boolean;
let topLeft: BoxCell = true;

if (typeof topLeft === 'boolean') {
  topLeft = 1;
} else {
  topLeft += 1; // <--- Type 'number' is not assignable to type 'never'.ts(2322)
}

topLeft is a fixed value in the code example but what I'm working on, involves the variable could either be a boolean or a number.

tsconfig.json

{
  "compilerOptions": {
    "target": "es2018",
    "module": "commonjs",
    "sourceMap": true /* Generates corresponding '.map' file. */,
    "outDir": "./dist" /* Redirect output structure to the directory. */,
    "strict": true /* Enable all strict type-checking options. */,
    "esModuleInterop": true
  }
}

Upvotes: 0

Views: 271

Answers (1)

Istvan Szasz
Istvan Szasz

Reputation: 1567

There's an open issue for this. You can use the binary infix addition operator instead, to fix this: topLeft = topLeft + 1

type BoxCell = number | boolean;
let topLeft: BoxCell = true;

if (typeof topLeft === 'boolean') {
  topLeft = 1;
} else {
  topLeft = topLeft + 1;  // <- no error
}

Upvotes: 1

Related Questions