React JS/Typescript中的空合并运算符

Pra*_*mar 7 .net javascript null-check typescript reactjs

我们有Null合并操作符.NET,我们可以使用如下

string postal_code = address?.postal_code;
Run Code Online (Sandbox Code Playgroud)

我们可以在React JS中做同样的事情吗?

我发现我们可以使用&&运算符

address.ts文件中

string postal_code = address && address.postal_code;
Run Code Online (Sandbox Code Playgroud)

我需要什么样的.net功能可以在typescript中使用react JS,这可能吗?

就像是:

string postal_code = address?.postal_code // I am getting the error in this line if I try to use like .NET
Run Code Online (Sandbox Code Playgroud)

Fen*_*ton 5

这是TypeScript中具有传奇色彩的问题#16的一项建议功能。

在此功能的ECMAScript规范确定之前,不会将它引入TypeScript中,因为希望TypeScript实现遵循该规范-因此,您会尽早获得,但在这种情况下不会太早。

它被称为以下任何一项:

  • 空传播算子
  • 存在运算符
  • 空合并运算符


T.J*_*der 5

2020 年更新:下面提到的 nullish-coalescing 运算符现在已在 ES2020 中完成该过程,就像可选的链接运算符一样,可以让您执行以下操作:

\n\n
let postal_code = address?.postal_code;\n// \xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92\xe2\x88\x92^\n
Run Code Online (Sandbox Code Playgroud)\n\n

使用可选链, if addressisnullundefined,postal_code将获得undefined其值。但如果address既不是null也不是undefinedpostal_code将得到 的值address.postal_code

\n\n
\n\n

JavaScript 没有空合并运算符(TypeScript 也没有,它主要限制自己添加类型层并采用在将其变成 JavaScript 的过程中相当远的功能)。有一个关于 JavaScriptnull合并运算符的提案,但它仅处于该过程的第一阶段。

\n\n

使用&&您所描述的习语是一种相当常见的方法:

\n\n
let postal_code = address && address.postal_code;\n
Run Code Online (Sandbox Code Playgroud)\n\n

如果addressnull(或任何其他 falsy\xc2\xb9 值),postal_code则将是相同的值;否则,它将是任何值address.postal_code

\n\n
\n\n

\xc2\xb9 假值为0, "", NaN, null, undefined, 当然还有false

\n