POV
POV

Reputation: 12025

How to simplify check if property exist in TypeScript?

Now I do the following check:

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

Could I beautify this check on property exist?

So, I mean this:

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

Upvotes: 3

Views: 4724

Answers (2)

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 250366

Edit

Since this was originally posted, typescript has added support for the ?. and the ?? operator. You can now now write the code as:

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

Both ?. and ?? check for null and undefined (not falsy values, which could be an issue before) so the code above is equivalent to:

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

Before 3.7

There is a proposal to add the ?. operator to JavaScript. The problem is that currently the optional chaining JS feature is not yet as stage 3, typescript will only support JS proposals that are at stage 3 when it comes to expression level syntax (when it comes to types they do their own thing). From the latest GitHub issue requesting optional changing :

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.

In the meantime you can use &&

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

Upvotes: 6

Yakov Fain
Yakov Fain

Reputation: 12376

TypeScript has the "in" type guard. For example, if you have a function that can take an argument of a union type, you can check the actual type given during the function invocation.

interface A { a: number };
interface B { b: string };

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

Upvotes: 4

Related Questions