我有一个班级的方法
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
因此我想做一个类型后卫,但所有的例子都无关紧要因为你可以输入一个类。
我想知道如何做到这一点。
最好的选择是内联检查。打字稿可以比在方法中隐藏的内容更好地计算出内联检查。
另一种选择是使用自定义类型防护并使用类型防护改变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
}
}