Tutorial

Type Aliases in TypeScript

TypeScript

While this tutorial has content that we believe is of great benefit to our community, we have not yet tested or edited it to ensure you have an error-free learning experience. It's on our list, and we're working on it! You can help us out by using the "report an issue" button at the bottom of the tutorial.

In this previous post, we learned how to use string literals in TypeScript. As a quick refresher, string literals allow us to use a string as a type.

Here’s a simple example to illustrate:

let pet: 'cat';

pet = 'cat'; // Ok
pet = 'dog'; // Compiler error

pet is of the type 'cat' so it only takes the value of 'cat'. Any other value results in an error.

String literals on their own aren’t particularly useful unless combined with Union Types like this:

let pet: 'cat' | 'dog';

pet = 'cat'; // Ok
pet = 'dog'; // Ok
pet = 'zebra'; // Compiler error

Our pet variable can now take either 'cat' or 'dog' as values because we used a Union Type.

But pet itself is not a type, it’s a variable. If we try to use it as a type, we will get an error.

let pet: 'cat' | 'dog';

pet = 'cat'; // Ok
pet = 'dog'; // Ok

let gator: pet; // error: 'pet' refers to a value, but is being used as a type here

To use the 'cat' | 'dog' type again, we have to repeatedly type it again. What if we have more than two pets? Yeah, you can see where this is going… Boring repetitive code. Luckily, there is a solution. We can use the keyword type to create a new type. So let’s refactor our code and create a type called pet.

type pet = 'cat' | 'dog';

let pet1: pet = 'cat'; // Ok
let pet2: pet = 'dog'; // Ok

let gator: pet = "horse"; // error

By creating a type we can use it anywhere in our code as if it where a number, string or any of the primitive or reference types. Any value that wasn’t declared as part of the pet type will result in an error if assigned to a variable of the pet type like gator in the code above.

In our example, we used a string type but a type can be any type.

Examples:

type num = 1 | 2; // number
type bool = true | false; // boolean
type obj = {a: 1} | {b: 2}; // object
type func = (() => string) | (() => void); // function

That’s it. Go have some fun with type. 😎🐱‍👓

0 Comments

Creative Commons License