5 Helpful Shorthands in TypeScript

Scott Hickmann
2 min readMay 10, 2022

--

TypeScript has lately become a very popular programming language. JavaScript is now being used for a wide variety of use cases (back-end with Node.js, web development with most web frameworks, app development with React Native, and even ML with TensorFlow.js).

With an increasing amount of large projects using JavaScript, many have now switched to writing their code in TypeScript, which provides types and backward compatibility through compilation.

In this article, I’d like to highlight several tricks I wish I had known early on when I started writing modern JavaScript and TypeScript code. This article is targeted mostly at those who already know about TypeScript and would like to improve their coding style.

The first few points apply to both TypeScript and modern JavaScript, while the later ones are TypeScript specific. With that said, let’s get right into it.

Null Coalescing Operator

If you want to resort back to a default value if a variable is null or undefined, you can use the null coalescing operator.

The above code will set displayName to 'Anonymous' since name is empty. The alternative would be to use the conditional operator, which is much wordier:

Maps and Sets

Use maps and sets when you need to! They can make your life much easier. If you need to check if an item is contained in a set you can simply write:

Not only is this much cleaner than using an array with .includes, it’s also more efficient as well as easier for a reviewer to understand.

Generics

Avoid using unknown or any as types as much as possible. There’s a much better way to deal with data that can take on multiple types: generics. For example, let’s say I need to use a function that nests data into a response object. I can do the following and preserve type safety:

As desired, the return value will have the type:

{
success: boolean;
data: T;
}

Assigning Instance Property in Constructor

When we write a class, we often need to set properties based on the arguments passed into the constructor. Luckily, there’s a shorthand way to do this in typescript. Instead of doing:

We can write:

Enums

Enums are definitely underrated. Before, when I created an event listener, I used to do it like this:

However, it’s now much better to do it like below in case you wish to rename the event you’re listening to. If you seek to change the event name 'user' to 'account', you can be assured that your code will still work and that you did not forget to copy-paste the change somewhere.

--

--