5 Typescript tricks for Angular

Alain Chautard
Angular Training
Published in
5 min readFeb 17, 2021

--

Typescript is a language that constantly involves and brings useful new features to the table. In this post, we’re going to take a look at five tips & tricks that can be used daily while working with Typescript.

Note that those tips don’t just apply to Angular and could be used with React, Vue.js, or even vanilla web app code that doesn’t use any framework/library.

1. Generating type data automatically

One of the best features of Typescript is that it allows us to use types for our data, using interfaces, enums, classes, and more.

The problem is that in many cases, we have to work with JSON data received from a third-party API or a backend service that can’t provide typed information.

The solution, in that case, is to use a tool such as json2ts.com:

With json2ts, all we need to do is copy/paste the JSON data for which we need type information, click the “Generate Typescript” button, and voila, the result is several Typescript interfaces with proper type inference:

export interface Option {
id: number;
displayOrder: number;
text: string;
}
export interface Question{
id: number;
examId: number;
text: string;
options: Option[];
}

2. Using Partial for objects in a temporary state

Say we want to create an instance of the Question object used above, but creating that object requires a couple of different steps. In the first step, I retrieve data for the question itself, and in the second step, I have to retrieve the response options.

As a result, I’m going to create an object that will be an incomplete Question at first, which looks like this:

let myQuestion: Question = {
id: 1102,
examId: 123,
text: "Which of the following is a prime number"
};t

The Typescript compiler would complain about the above code because the question object does not have an options property. A possible solution would be to change the Question type to make options… optional by using the question mark in our interface:

export interface Question {
id: number;
examId: number;
text: string;
options?: Option[];
}

But that is not ideal if those options are indeed required. A much better solution is to indicate that we are OK with an object that is partially created using the Partial generic type from Typescript:

let myQuestion: Partial<Question> = {
id: 1102,
examId: 123,
text: "Which of the following is a prime number"
};

Now the compiler is fully happy with the above code, and we didn’t have to alter our interfaces at all!

myQuestion is now an object that implements a sub-set of the Question interface, with all properties being optional.

Pass your Angular certification exam today

3. Using union types for all sorts of things

We can use Union types for several different scenarios. One of my favorite use cases is to replace enums as they aren't incredibly convenient in Typescript.

The following enum:

export enum Color {RED = ‘red’, BLUE = ‘blue’, WHITE = ‘white’}

can be replaced with union types like so:

export type Color = 'red' | 'white' | 'blue';

I can now use the Color type and assign a string value to it, which is a win-win as my code is strongly typed, and I get immediate access to all of the string type functions. The values of Color are both strings and instances of Color, which is excellent.

From a performance perspective, union types are even better as they disappear entirely from your compiled code at runtime, which contrasts with enums that get compiled into a voluminous nightmarish function structure.

You can find more examples of why union types rock in this short tutorial: Union types in Typescript.

4. Using the new ?? operator

Since Typescript 3.7, the language features a ?? operator known as Nullish Coalescing Operator, also available in modern Javascript in most browsers.

This operator aims to remove such code from our codebases:

if (value !== null && value !== undefined) {
a = value;
} else {
a = 'some default value';
}

Now, smart Javascript developers used to simplify the above code using the logical OR operator as follows:

a = value || 'some default value';

But the above example has a few caveats, as in Javascript, 0, NaN, and empty strings are being treated as falsy values, which means that if value = 0 or value = “”, the default value would be assigned to a.

The ?? operator fixes this behavior:

a = value ?? 'some default value';

As illustrated by those examples:

console.log(0 ?? 42);   // outputs 0
console.log("" ?? 42); // outputs ""

Using the ?? operator is an excellent habit to take instead of using the legacy options outlined above.

5. Path mapping to simplify verbose imports

Typescript imports in large projects can quickly become difficult to read. Something reasonably common to see is import declarations such as this one:

import {something} from '../../../../../shared/shared.service'

That said, imports don’t have to be that long. Typescript has a solution for that called path mapping.

Such mappings are added to the tsconfig.json file, which results in the following, much more readable declaration:

import {something} from 'shared/shared.service'

You can read my blog post “Path mapping with Typescript” for more information about that feature.

My name is Alain Chautard. I am a Google Developer Expert in Angular, as well as consultant and trainer at Angular Training where I help web development teams learn and become comfortable with Angular.

If you enjoyed this Angular tutorial, please clap for it or share it. Your help is always appreciated. You can also subscribe to Medium here.

--

--