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

OPV*_*OPV 3 typescript

现在我做以下检查:

 return this.profile.organization ? this.profile.organization.shifts : null;
Run Code Online (Sandbox Code Playgroud)

我可以美化这个对财产存在的检查吗?

所以,我的意思是:

this.profile.organization.shifts || '';
Run Code Online (Sandbox Code Playgroud)

Tit*_*mir 6

编辑

由于本文最初发布,TypeScript 添加了对?.and??运算符的支持。您现在可以将代码编写为:

this.profile.organization?.shifts ?? ""
Run Code Online (Sandbox Code Playgroud)

?.??检查nullundefined(不是假值,这可能是之前的问题),因此上面的代码相当于:

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

3.7之前

有建议添加?。JavaScript 的运算符。问题是,目前可选的链式 JS 功能尚未达到第 3 阶段,当涉及到表达式级别语法时,Typescript 将仅支持处于第 3 阶段的 JS 提案(当涉及到类型时,它们会做自己的事情)。来自请求可选更改的最新 GitHub问题:

在向 TS 中添加功能多次被烧毁之后,却在最后一秒把语义地毯从我们脚下拉了出来,实际上没有多少赞成票可以让我们添加一个可能在某个时候彻底改变运行时行为的功能将来。

在此期间您可以使用&&

this.profile.organization && (this.profile.organization.shifts || '')
Run Code Online (Sandbox Code Playgroud)