(我是一个老式的C / C ++人,只是在学习打字稿。)
我有一些这样的代码:
class myClass {
v: string | null = null
setVtoNonNull() { this.v = "hi" }
method() {
if (!this.v)
this.setVtoNonNull()
// now at this point v is definitely not null
// how do I tell typescript that?
const s: string = this.v // <<<< typescript gives error here
}
}
在method
中,如何告诉打字稿在setVtoNonNull()
调用之后,局部变量v
不为null?我知道我可以在设置v!
之后的任何地方使用v
(但是如果我经常使用v
的话,这很烦人),或者我可以做这样一个骇人的骇客:
v = v!
但这只是为了编译时的清洁度而在运行时会花费周期。是否有编译器指令或我可以使用的东西?
答案 0 :(得分:1)
我会做这样的事情:
class myClass {
v: string | null = null;
setVtoNonNull(): string {
if (!this.v) {
this.v = "hi";
}
return this.v;
}
method() {
const s: string = this.setVtoNonNull();
}
}
答案 1 :(得分:-2)
这种失败是打字稿的目的。无论如何,由于TypeScript会推断变量类型,所以我建议您使用类似的
class myClass {
v: any = null
// ... rest of your conde
}