TypeScript Advanced Types and Guards

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.


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.


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

Type Guards

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

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!



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store