现在我进行以下检查:
return this.profile.organization ? this.profile.organization.shifts : null;
我可以美化这个对属性存在的检查吗?
所以,我的意思是:
this.profile.organization.shifts || '';
最佳答案
编辑
自从最初发布以来,typescript 增加了对 ?.
和 ??
运算符的支持。您现在可以将代码编写为:
this.profile.organization?.shifts ?? ""
?.
和 ??
都检查 null
和 undefined
(不是假值,可能是之前的一个问题)所以上面的代码相当于:
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/