【问题标题】:Typescript functions that check for null / undefined检查 null / undefined 的打字稿函数
【发布时间】:2019-06-27 13:58:30
【问题描述】:

我正在使用VS Code,它在使用Typescript 时有很大帮助,因为它可以告诉您何时存在当前问题而无需转译。 我将TypescriptnodeJS 一起使用,效果非常好。

我唯一遇到的问题是所谓的“空/未定义检查函数”。

看这个例子:

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


【解决方案1】:

类型缩小适用于特定的句法结构。 if (obj.prop != undefined) 就是这样一种构造,它将通知编译器 prop 不能未定义。

在您的情况下,您在属性中执行检查。 Typescript 不会跟随 getter 的实现来查看它是否执行 null 检查。

您可以使用自定义类型保护(一种具有特殊语法的方法/函数,可以通知编译器类型副作用):

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) 又是具有 someProperty 类型的属性 string 的对象。由于User 已经有someProperty,因此此交集中的someProperty 类型将有效地解决User['someProperty'] & string = (string | undefined) & string = string 从结果类型中的someProperty 类型中删除undefined

【讨论】:

  • @MuratKaragöz 我添加了一个解释,希望它能让事情更清楚一点
【解决方案2】:

您可能想要更改:

myUser.someProperty != undefined

typeof myUser.someProperty !== "undefined"

这将检查输入而不是值。

【讨论】:

  • myUser.someProperty != undefined 是一个有效的..第二个无效
  • 没关系。如果变量的类型为undefined,则该变量将具有原始值undefined。现代浏览器不允许您覆盖undefined-type。但是propertyName !== undefinedtypeof ...-check 短,所以我更喜欢那个。
猜你喜欢
  • 2018-05-22
  • 1970-01-01
  • 2021-05-23
  • 2020-07-10
  • 2022-07-20
  • 1970-01-01
  • 1970-01-01
  • 2021-11-19
相关资源
最近更新 更多