Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

typescript

What are type aliases in TypeScript?

Programming Bytes

Overview

In TypeScript, type aliases are used to assign a name for any type. It doesn't create a new type. Instead, it provides a name for the type.

Create type alias

To create a type alias, we need to use the type keyword.

type gender = "male" | "female" | "nonbinary";

let male:gender = "male";
let female:gender = "female";
let nonbinary:gender = "nonbinary";

console.log(male, female, nonbinary)
Creating a type alias

In the code above, we have created a type alias with the name gender. The gender type can have one of the following values: "male", "female", or "nonbinary".

When we try to assign a value other than the configured value, we get a compilation error. The code widget below demonstrates this case:

type gender = "male" | "female" | "nonbinary";

// assigning value which is not configured will throw compilation error 
let err:gender = "gen";
Type alias error

Examples

type alphaNumeric = string | number;

let num:alphaNumeric = 10;
let str:alphaNumeric = "ten";

type Point = {
  x: number;
  y: number;
};

let pt:Point = {x: 10, y: 20};

// obj type variable can have any one of the below value
type obj = {val: 1} | {val: 2}; 

// obj type variable can have any one of the below value
type func = (() => string) | (() => void);
Type alias example

Explanation

  • Line 1: We create a type alias with the name alphaNumeric . The alphaNumeric type can have either a string or a numeric value.
  • Lines 6–9: We create a type alias with the name Point. The Point type is an object that has two numeric properties, x and y .
  • Line 14: We create a type alias with the name obj. The value of the obj type should either be {val: 1} or {val: 2} . Similarly, we create a type for func in line 17.

RELATED TAGS

typescript
RELATED COURSES

View all Courses

Keep Exploring