在打字稿中替换Angular2的Elvis算子 [英] Replacement of Elvis Operator of Angular2 in Typescript

查看:114
本文介绍了在打字稿中替换Angular2的Elvis算子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在打字稿中是否有任何操作符使用similer到 elvis Operator of angular2,我的意思是说
让我知道我必须从对象获取密钥像这样:

Is there any operator in the typescript which is used similer to Elvis Operator of angular2, i mean to say let supppose i have to get key from object like this:

this.myForm.name.first_name

如果first_name不存在则会抛出错误 first_name of undefined

and in case first_name does't exist so it will throw error first_name of undefined,

是的,我可以使用三元运算符这样的打字机来解决这个错误

yes i can handel this error using Ternary operator of typescript like this

this.myForm.name ? this.myForm.name.first_name : ''

但有时键太长,

所以在打字稿中有任何像 Elvis Operator 一样的运营商的angular2,这样我就可以这样使用了

so is there any operator like Elvis Operator of angular2 in the typescript so that i can use like this

this.myForm?.name?.first_name


推荐答案

TypeScript中没有elvis运算符,据我所知,也没有可比性。

There is no elvis operator in TypeScript and, as far as I know, nothing comparable, either.

有关参考,请参阅
的功能请求建议:安全导航操作员,即X?.Y 未实施的解释如下(在我看来, ,是一个有效的理由):

For a reference see the feature request at Suggestion: "safe navigation operator", i.e. x?.y. The explanation for not implementing it is the following (which, in my opinion, is a valid reason):


现在关闭它。由于没有任何特定于TypeScript的内容需要在表达式级别上进行,因此这种大型操作员更改应该在ES规范委员会而不是在此处进行。

Closing this for now. Since there's not really anything TypeScript-specific that would require this at expression level, this kind of big operator change should happen at the ES spec committee rather than here.

一般重新评估这个问题的绊网将是一个具体的ES提案,进入下一阶段,或者ES委员会普遍认为这个特征很长时间不会发生(这样我们就可以定义我们自己的语义并合理地确定他们会赢)。

The general tripwires for re-evaluating this would be a concrete ES proposal reaching the next stage, or a general consensus from the ES committee that this feature wouldn't happen for a long time (so that we could define our own semantics and be reasonably sure that they would "win").

该表示法的替代方法是使用逻辑AND运算符,try / catch或辅助函数喜欢 getSafe(()=> this.myForm.name.first_name),如这篇文章

Alternatives to that notation would be to use the logical AND operator, try/catch or a helper function like getSafe(() => this.myForm.name.first_name) as described in this post.

更新2017年7月:正如JGFMK在评论中指出的那样,有一个名为 JavaScript的可选链接。如果/当提案到达阶段4时,它将被添加到语言规范中。

Update July 2017: As JGFMK pointed out in the comments, there is an ECMAScript proposal called Optional Chaining for JavaScript. If/when the proposal reaches Stage 4, it will be added to the language specification.

这篇关于在打字稿中替换Angular2的Elvis算子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆