Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to simplify check if property exist in TypeScript?

Tags:

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 || '';
like image 460
OPV Avatar asked Oct 23 '25 10:10

OPV


1 Answers

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 || '')
like image 56
Titian Cernicova-Dragomir Avatar answered Oct 25 '25 23:10

Titian Cernicova-Dragomir



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!