【问题标题】:How to simplify check if property exist in TypeScript?如何简化检查 TypeScript 中是否存在属性?
【发布时间】:2019-08-23 12:24:41
【问题描述】:

现在我进行以下检查:

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

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

所以,我的意思是:

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

【问题讨论】:

标签: typescript


【解决方案1】:

编辑

自从最初发布以来,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 请求可选更改的问题:

在通过向 TS 添加功能多次烧毁后,只是在最后一秒将语义地毯从我们下面拉了出来,真的没有多少赞成票会让我们添加一个可能会彻底改变运行时行为的功能在未来的某个时间点。

同时你可以使用&&

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

【讨论】:

    【解决方案2】:

    TypeScript 具有“in”类型保护。例如,如果您有一个可以接受联合类型参数的函数,您可以检查函数调用期间给出的实际类型。

    interface A { a: number };
    interface B { b: string };
    
    function foo(x: A | B) {
        if ("a" in x) { 
            return x.a;
        }
        return x.b;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-24
      • 1970-01-01
      • 2015-05-22
      • 2014-08-11
      • 2017-01-15
      相关资源
      最近更新 更多