Null coalescing operator in React JS/ Typescript [duplicate]

拜拜、爱过 提交于 2019-12-01 16:53:47

This is a proposed feature in TypeScript, under the legendary Issue #16

It won't be introduced into TypeScript until the ECMAScript spec for this feature is firm as there is a desire for the TypeScript implementation to follow that specification - so you'll get it early, but not massively early in this case.

It is referred to as any of the following:

  • Null Propagation Operator
  • Existential Operator
  • Null Coalesce Operator

JavaScript doesn't have a null-coalescing operator (nor does TypeScript, which mostly limits itself to adding a type layer and adopting features that are reasonably far along the path to making it into JavaScript). There is a proposal for a JavaScript null-coalescing operator, but it's only at Stage 1 of the process.

Using the && idiom you've described is a fairly common approach:

let postal_code = address && address.postal_code;

If address is null (or any other falsy¹ value), postal_code will be that same value; otherwise, it will be whatever value address.postal_code was.


¹ The falsy values are 0, "", NaN, null, undefined, and of course false.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!