TypeScript 是否有 Null 条件运算符

Does TypeScript have a Null-conditional operator

有没有像?这样的运算符。在 TypeScript 中可以检查变量是否为空或未像 Kotlin 那样定义?喜欢

person?.getName()?.firstName ?: "None"

不,截至目前安全导航运算符仍未在 Typescript 中实现: https://github.com/Microsoft/TypeScript/issues/16

但是根据最新的标准化会议记录,它已经被提议,所以可能是 v3 :)

https://github.com/tc39/agendas/blob/master/2017/07.md

实际上这与javascript空安全discussion that is mentioned in this answer有关。我猜他们希望在使用打字稿之前 javascript 支持它。

我遇到过同样的情况,下面的方法对我有用。

首先,我定义了一个单独的 class 和一个 属性 可以是 null:

export class Foo {
    id: number; //this can be null
}

然后在我的主要 class 中,我将 属性 foo 设置为这个新类型:

foo: Foo

之后,我可以这样使用它了:

var fooId = (this.foo || ({} as Foo)).id;

这是我在当前版本的 TypeScript 中最接近的空传播。

我在我的代码中使用它来检查 null

this.firstname = (this.firstname != null) ? this.firstname : this.firstname;

这可以做到 v3 出来

是的,从 Typescript 3.7 开始,您现在可以通过 optional-chaining

执行此操作
person?.getName()?.firstName

被转译为

let firstName = person === null || person === void 0 ? void 0 : (_person$getName = person.getName()) === null || _person$getName === void 0 ? void 0 : _person$getName.firstName;

注意空值检查。如果例如 person 被定义为

,这将按预期工作
let person:any = null; //no runtime TypeError when calling person?.getName()

但是如果人被定义为

let person:any = {};//Uncaught TypeError: person.getName is not a function

另请参阅此 similar Whosebug question

真正好的答案在 Andreas 的评论中。从 Typescript 3.7 开始,您的示例将按如下方式实现:

person?.getName()?.firstName ?? "None"

https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html#nullish-coalescing

不仅 typescript 支持它(从 3.7.2 版本开始)。 javascript 现在也支持它(自 ES2020 起)。

  • 实际上这意味着您可以在 Angular 这样的框架中使用它 (since v9 which supports typescript 3.7).

  • 但特别是现在 它在 ES2020 规范中,我们将会看到它 无处不在。

如果没有电子邮件,这会将 item 设置为 null

let item = user?.email;