Tutorial

How To Use Type Aliases in TypeScript

Updated on December 17, 2020
authorauthor

Alfred M. Adjei and Ceora Ford

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 our products

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!

Become a contributor for community

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

DigitalOcean Documentation

Full documentation for every DigitalOcean product.

Resources for startups and SMBs

The Wave has everything you need to know about building a business, from raising funding to marketing your product.

Get our newsletter

Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

New accounts only. By submitting your email you agree to our Privacy Policy

The developer cloud

Scale up as you grow — whether you're running one virtual machine or ten thousand.

Get started for free

Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

*This promotional offer applies to new accounts only.