Tutorial

How To Use Type Aliases in TypeScript

Updated on December 17, 2020
Default avatar

By Alfred M. Adjei

How To Use Type Aliases in TypeScript

Introduction

It’s important to create dynamic and reusable code. The Don’t-Repeat-Yourself rule or DRY is an important principle to follow when writing code in TypeScript. Using TypeScript aliases will help you to accomplish this.

In this tutorial, you will refactor code that uses string literals to include aliases. You will be able to use and understand TypeScript aliases.

Prerequisites

To successfully complete this tutorial, you will need the following:

Step 1 — Using String Literals

String literals allow us to use a string as a type. Create a variable called pet and instead of setting it equal to a traditional type like string, assign 'cat' as the type:

let pet: 'cat';

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

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

In the above code snippet, assigning pet to 'dog' will cause an error since the only valid value for pet is 'cat'.

String literals become even more powerful when used with union types. Union types are used to define values that can be of more than one type. With union types, the | character is used to separate the different possible types:

let pet: 'cat' | 'dog';

The pet variable can now take either 'cat' or 'dog' as values. Assigning pet to any other string value will result in an error:

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

You can learn more about union types in this article.

But pet itself is not a type. It’s a variable. Using pet as a type will produce an error.

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

Since pet is not a valid type, the 'cat' | 'dog' type has to be repeated again. This can make your code unnecessarily repetitive. Using the type alias can solve this.

Step 2 — Using Type Alias

To implement the type alias, use the type keyword to create a new type. Use type to declare pet as a type:

type pet = 'cat' | 'dog';

By creating a type, you can use pet anywhere in your code as if it were a number, string or any of the primitive or reference type:

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

Any value that wasn’t declared as part of the pet type will result in an error:

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

The previous example used type with a string value. But a type can used with any type.

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

Now that you know how to use the type alias type, you can make your code more generic and less repetitive.

Conclusion

In this article, you used the TypeScript type alias to refactor your code. Using type can help you to create clean code that is not unnecessarily repetitive.

As a next step, you may want to take your TypeScript knowledge to the next level by learning about generics. This article about TypeScript generics is a great resource to jump into.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about us


About the authors
Default avatar
Alfred M. Adjei

author



Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
Leave a comment


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Get our biweekly newsletter

Sign up for Infrastructure as a Newsletter.

Hollie's Hub for Good

Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

Become a contributor

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

Welcome to the developer cloud

DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

Learn more
DigitalOcean Cloud Control Panel