首页 > 解决方案 > 打字稿类型保护布尔结果从不

问题描述

我有topLeft一个布尔变量,它的类型可以是numberbooleantopLeft将变为一个数字,如果它已经是一个数字,则将其加一。我有一个类型保护,topLeft如果它是一个布尔值,它会变成一个数字。但是在 else 语句中,变量的结果是never类型。

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是代码示例中的固定值,但我正在处理的涉及变量可以是布尔值或数字。

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
  }
}

标签: typescript

解决方案


这有一个未解决的问题。您可以改用二进制中缀加法运算符来解决此问题:topLeft = topLeft + 1

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

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

推荐阅读