Vin*_*t J 8 types predicate typescript
我有一个这样定义的类
class Foo {
value: string | null;
constructor(){
this.value = null;
}
private ensureValueExists():this.value is string{ //type predicate is not legal
this.value = "bar";
return true;
}
doStuffWithValue(){
this.ensureValueExists();
return 5 + this.value; //ERROR, this.value can be null
}
}
Run Code Online (Sandbox Code Playgroud)
我希望 EnsureValueExists 方法能够告诉编译器 this.value 确实是一个字符串并且可以安全使用。是否有特殊的语法可以使用,或者目前对于方法来说 TS 无法实现?
jca*_*alz 10
您可以使用缩小范围的断言方法this
。尽管与实现断言函数的 PR microsoft/TypeScript#32695相关的提交表明这是可能的,但文档中对此的支持并不是特别清楚。
所以在你的情况下它看起来像:
private ensureValueExists(): asserts this is { value: string } {
this.value = "bar";
}
Run Code Online (Sandbox Code Playgroud)
(请注意,您不能在断言函数/方法中返回任何内容),然后执行以下操作:
doStuffWithValue() {
this.ensureValueExists();
return 5 + this.value; // okay
}
}
Run Code Online (Sandbox Code Playgroud)
肯定有与断言函数和方法相关的警告,但由于您仅在 上进行操作this
,因此您不会在这里遇到它们。