javascript - 返回值存在的类型脚本类型保护
问题描述
我有一个类的方法
isReadyToSumNumbers() {
return Boolean(
this.arithmeticOperation && this.slots["1"] && this.slots["2"]
);
}
这显然表明如果所有 3 个值都存在,则返回 true。
然后我有另一种使用此方法的方法,如下所示:
if (this.isReadyToSumNumbers()) {
const newValue = this.arithmeticOperation(
this.slots["1"],
this.slots["2"]
).toString();
...
但是打字稿显示了一个错误,this.arithmeticOperation can be undefined
因此我想进行类型保护,但所有示例都无关紧要,因为您可以键入保护类 | .
我想知道它是怎么做到的。
解决方案
最好的选择是内联检查。Typescript 可以比隐藏在方法中的检查更好地找出内联检查。
另一种选择是使用自定义类型保护并使用类型保护更改this
类型:
class Test {
isReadyToSumNumbers(): this is Test & {
arithmeticOperation: (a: number, b: number) => number;
slots: {
1: number,
2: number
}
} {
return Boolean(
this.arithmeticOperation && this.slots["1"] && this.slots["2"]
);
}
m() {
if (this.isReadyToSumNumbers()) {
const newValue = this.arithmeticOperation(
this.slots["1"],
this.slots["2"]
).toString();
}
}
arithmeticOperation?: (a: number, b: number) => number;
slots: {
1?: number,
2?: number
}
}
推荐阅读
- java - 在 Flink 中使用 mysql-connector-java:连接到 mysql >= 8.0.16 时找不到合适的驱动程序
- javascript - 为什么在对象数组中搜索不起作用?
- android - 如何将 contentDescription 提供给 SwitchPreference 以进行 Accessibilty/Talkback?
- regex - Google Sheets RegEx:在不允许字母的情况下设置数字范围
- python - 我正在尝试在 django 中创建登录/注销功能,但出现以下错误
- angular6-json-schema-form - 光标在 Angular6 Json Schema Form 输入字段中跳转到末尾
- java - 在 AWS 中,如何在 describe-image api 中指定区域以获取该区域的 AMI Id
- python - PySpark:对于每一行,根据条件计算另一个表
- javascript - 我可以在 Node.js 进程之间有效地传输 Tensorflow.js 张量吗?
- sql-server - SQL Server - 使用列数据类型作为用户输入构建表 - 如何验证用户输入