TypeScript Advanced Types and Guards

Adam Altmark
3 min readNov 19, 2020

A big part of TypeScript is catching potential errors before they happen. To empower this tool, using proper types is necessary. In this blog, I will outline a few of the advanced types included with TypeScript.

Intersection

An intersection type allows you to combine multiple types. Let’s consider a college course.

A teacher’s assistant will have responsibilities, but they also are a student. Now, when you create a TA object:

You can see that for the intersection you need properties from both.

Union

Union types, on the other hand, say an object can be one thing OR another. For a simple example:

This one is pretty straightforward — the type can either be a number or a string.

Type Guards

Where things become interesting is when you combine these two types. Let’s say you had a student, where you did not know if they were a TA or not.

This is a union type — saying it can either be a normal student OR a teacher’s assistant (which is an intersection). If you wanted to print out all properties of this student, you need to make sure that you are not attempting to print properties that are not there.

As you can see, TypeScript is throwing an error because it is unsure if the unknown student will have that property. In this case, you can use an ‘In’ Type Guard.

Let’s say you had a similar setup, but using classes instead of types.

Students and assistants need to attend class but only assistants can grade papers. Now if you had a similar union type:

You’ll find that you cannot simply call gradePaper.

Calling attend class is fine because both the student class and assistants have that method, however only assistants can grade papers. Here you can use the ‘Instance Of’ Type Guard.

Discriminated Unions

Another guard comes about when dealing with discriminated unions. These union types have a field that is always declared as a literal. This literal allows TypeScript to distinguish between types.

Now, if you wanted to check for speed, you could using the type literal in a switch statement as so:

Even though the boat types speed properties were labeled differently, the switch statement allows us to safely move between both!

--

--