Optional Chaining into the ES2020, not a full screen `x && x.yyy`

TypeScript Microsoft program manager  Daniel Rosenwasser  announced Optional Chaning (?.) into the TC39 Stage 4 status , which means that this feature is now a standard part of the ES2020.

Optional Chaining is the first TypeScript the first issue tracker 16 issue, filed five years ago, to know that there are currently a total of up to 23 000 issue. At that time TC39 no formal proposal, the years developers have been required to achieve this feature, but in order not to ECMAScript conflicting recommendations, has yet to achieve, contrary TS development team has been instrumental in pushing the proposal to standardize and ultimately push and all JavaScript and TypeScript developers.

TypeScript in version 3.7 released last month, the official brought Optional Chaining properties , now goes a step further, this feature into the ECMAScript standard.

Optional Chaining feature is mainly used to protect the property appear in the path null and undefined value, like C # and other languages ​​have syntactic sugar for accessing the property chain, anywhere in the object hierarchy process null and undefined conditions encountered, You can perform normal, and does not throw an error.

Specifically, when the property value access to the depths of the tree structure, the intermediate node generally needs to check whether there is:

var street = user.address && user.address.street;

Many objects or API returns a null / undefined, and might want to extract attributes from the result when the result is not null:

var fooInput = myForm.querySelector('input[name=foo]')
var fooValue = fooInput ? fooInput.value : undefined

Optional Chaining operator allows developers to directly handle the situation in a simple manner, without performing repetitive operations, or the use of temporary variables are allocated intermediate results:

var street = user.address?.street
var fooValue = myForm.querySelector('input[name=foo]')?.value

因为是保护访问属性链时的 null 与 undefined,所以 Optional Chaining 运算符也叫做“安全导航运算符”,TC39 标准中给出的该运算符是“?.”,它的语法可以适用于三种场景:

obj?.prop       // 自判断静态属性访问
obj?.[expr]     // 自判断动态访问
func?.(...args) // 自判断函数或方法调用

对于开发者来说,再也不用看到满屏`x && x.yyy`了。

Guess you like

Origin www.oschina.net/news/111888/optional-chaining-moved-to-stage-4