typescript - 如何简化检查 TypeScript 中是否存在属性?

标签 typescript

现在我进行以下检查:

 return this.profile.organization ? this.profile.organization.shifts : null;

我可以美化这个对属性存在的检查吗?

所以,我的意思是:

this.profile.organization.shifts || '';

最佳答案

编辑

自从最初发布以来,typescript 增加了对 ?.?? 运算符的支持。您现在可以将代码编写为:

this.profile.organization?.shifts ?? ""

?.?? 都检查 nullundefined(不是假值,可能是之前的一个问题)所以上面的代码相当于:

var _a, _b;
_b = (_a = this.profile.organization) === null || _a === void 0 ? void 0 : _a.shifts, (_b !== null && _b !== void 0 ? _b : "");

3.7 之前

有一个建议添加?。 JavaScript 的运算符。问题是目前可选的链接 JS 功能还没有到阶段 3,typescript 将只支持在表达式级别语法(当涉及到他们自己做的类型时)处于阶段 3 的 JS 提案。来自 latest GitHub要求可选更改的问题:

After being burned multiple times by adding features to TS only to have the semantic rug pulled out from under us at the last second, there is seriously no number of upvotes that would have us adding a feature that could potentially drastically change runtime behavior at some point in the future.

同时你可以使用 &&

this.profile.organization && (this.profile.organization.shifts || '')

关于typescript - 如何简化检查 TypeScript 中是否存在属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55470328/

相关文章:

javascript - Angular 4 : cannot subscribe observable value from CanActivate AccessGuard

typescript - 我可以将 TypeScript 类型与 io-ts 一起使用吗?

Typescript 不会提示缺少或太多对象属性

javascript - typescript 错误对象可能为空?为什么,如何禁用?

TypeScript:使用字符串文字时的类型推断

javascript - 仅从 Angular 2 组件中的 rxjs 导入所需的功能

javascript - 我如何循环动画循环进度组件

Angular - 在另一个组件中动态注入(inject)一个组件

rest - 需要帮助理解 angular2 中的接口(interface)和/或抽象类

javascript - 将 JSON 数据复制到数组中