3

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 || '';
POV
  • 11,293
  • 34
  • 107
  • 201
  • 2
    Similar to, the answer applies but the question is phrased differently ..https://stackoverflow.com/questions/50211847/typescript-optional-types/50211941#50211941 – Titian Cernicova-Dragomir Apr 02 '19 at 08:42
  • Sadly, there is no null-conditional operator as C# and many other languages does. See https://stackoverflow.com/questions/45441086/does-typescript-have-a-null-conditional-operator and https://stackoverflow.com/questions/15260732/does-typescript-support-the-operator-and-whats-it-called – ShamPooSham Apr 02 '19 at 08:43
  • But I usually use the '&&' operator. If the left-hand expression is [truthy](https://developer.mozilla.org/en-US/docs/Glossary/Truthy), it will evaluate the right-hand expression – ShamPooSham Apr 02 '19 at 08:46

2 Answers2

5

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 || '')
Titian Cernicova-Dragomir
  • 230,986
  • 31
  • 415
  • 357
4

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;
}
Yakov Fain
  • 11,972
  • 5
  • 33
  • 38