我正在使用VS Code
,它在使用Typescript
时有很大帮助,因为它告诉您当前存在问题而无需转译。 我正在nodeJS
一起使用Typescript
,效果非常好。
我唯一的问题是所谓的"空/未定义的检查函数"。
请参阅此示例:
class User {
public someProperty: string | undefined;
// ...
public get canDoSomething() {
return this.someProperty != undefined;
}
}
let myUser: User = ...
这很好用:
if (myUser.someProperty != undefined) {
// at this point myUser.someProperty is type string only (as it cannot be undefined anymore
}
但是这失败
了if (myUser.canDoSomething) {
// because typescript still thinks that myUser.someProperty is string | undefined and not just string, even though this method checks for that.
}
知道我会怎么告诉打字稿吗?因为有时这样的方法比不断比较属性与未定义本身更干净。
谢谢
类型缩小适用于特定的语法结构。if (obj.prop != undefined)
就是这样一种构造,它将通知编译器prop
不能未定义。
在您的情况下,您执行属性中的检查。Typescript 不会遵循 getter 的实现来查看它是否执行空检查。
您可以使用自定义类型保护(具有特殊语法的方法/函数,用于通知编译器类型副作用):
class User {
public someProperty: string | undefined;
public canDoSomething() : this is this & { someProperty: string} {
return this.someProperty != undefined;
}
}
let myUser: User = new User
if (myUser.canDoSomething()) {
myUser.someProperty.big()
}
我建议坚持使用更简单if (myUser.someProperty != undefined)
,除非您有充分的理由封装支票。
编辑
this is this & { someProperty: string}
通知编译器调用此方法的对象类型(this
)现在已经(is
)更改为新类型(交集this & { someProperty: string}
)。
交集中的this
this & { someProperty: string}
充当当前类的类型(称为多态this
),并且将是User
或派生自用户的任何类(可以使用User
而不是this
但它不适用于派生类。
与{ someProperty: string}
的交集(&
)意味着检查后的类型既是我们之前的任何类(this
),也是具有类型string
属性someProperty
的对象。由于User
已经someProperty
此交叉点中的someProperty
类型将有效地User['someProperty'] & string = (string | undefined) & string = string
从结果类型中的someProperty
类型中删除undefined
。
您可能希望更改:
myUser.someProperty != undefined
自
typeof myUser.someProperty !== "undefined"
这将检查类型而不是值。