【发布时间】:2019-06-27 13:58:30
【问题描述】:
我正在使用VS Code,它在使用Typescript 时有很大帮助,因为它可以告诉您何时存在当前问题而无需转译。
我将Typescript 与nodeJS 一起使用,效果非常好。
我唯一遇到的问题是所谓的“空/未定义检查函数”。
看这个例子:
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语句不应该是:if (myUser.canDoSomething())吗?没有括号,您不会调用类型保护,只是检查函数是否已定义。从 TypeScript 的角度来看,someProperty仍然可以是undefined。 -
@MehmetSeckin 不,它是类属性,而不是方法,请注意
get -
啊,对,我的错。我才意识到这是一个类属性。
-
你可以使用 isNullOrUndefined(value)
标签: typescript