typescript - 打字稿类型保护布尔结果从不
问题描述
我有topLeft
一个布尔变量,它的类型可以是number
或boolean
。topLeft
将变为一个数字,如果它已经是一个数字,则将其加一。我有一个类型保护,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
}
}
解决方案
这有一个未解决的问题。您可以改用二进制中缀加法运算符来解决此问题:topLeft = topLeft + 1
type BoxCell = number | boolean;
let topLeft: BoxCell = true;
if (typeof topLeft === 'boolean') {
topLeft = 1;
} else {
topLeft = topLeft + 1; // <- no error
}
推荐阅读
- arm - 如何在 ARM 中找到十六进制数字的符号扩展?
- go - 如何检查值是否动态实现接口?
- java - 十六进制数据不会在我的 BLE 扫描仪应用程序中打印
- php - 如何在 Api-Platform 中为虚拟属性引入过滤功能?
- spring - AWS:基于 Cognito 身份验证角色限制 API 对资源的访问
- autodesk-forge - 尝试对 Forge BIM360 API 进行 API 调用时出现错误?
- python - TypeError:“元组”对象不可调用?
- javascript - 如何获取 MOV 文件格式的 videoWidth、videoHeight?
- ruby - 在本地服务器上运行 jekyll 时,出现“多个 gemspecs 错误”
- docker - Jenkins 管道在 docker 中构建