Type Aliases in TypeScript

The Type Aliases in Typescript allow us to give a custom name to an existing type. This is useful when you wish to reuse an existing type as it provides a reusable definition.

Creating Type Alias

The syntax starts with the keyword type followed by the name you wish to give to the new type. It is then followed by an assignment operator and then the type to which you want to assign the name.

type aliasName = anyType;

The following example creates Person type, which is an object with property name & age.

type Person = {
  name: string;
  age:number;
}

Now, we can use the type Person to create an object as shown below

let person:Person;

As you can see from the image below, hovering over the person will show its type as Person. Intellisense shows only two properties age & name.

type Person = {
  name: string;
  age:number;
}

let person:Person = {
  name:"Sachin",
  age:50
}

Type Aliases for Primitive Types

You can create a type alias for any existing type. This includes the primitive values also. The following example creates an alias numType for number type.

type numType= number;

let a:numType=10
let b:numType=20
let c=30

console.log(a+b+c)   //50

Union Types and Type Aliases

Union Types in Typescript allows a variable to have the ability to store a value of several types. We define union types by using a pipe (|) to separate each of the possible types.

For Example in the following code, the variable a can accept both string & number but not a boolean.

let a:number|string
 
a = 1         //ok
a = "hello"   //ok
 
a=true        //Type 'boolean' is not assignable to type 'string | number'

The Type Aliases help us to create an alias for a union type and use that alias.

type stringOrNumber =  number | string;
type yesNoType = "yes" | "no";
type statusType = "Pending" | "Started" | "Finished"

In the example, the new type stringOrNumber represents the union of number | string.

type stringOrNumber =  number | string;       //Type Alias for a Union Type

let a:stringOrNumber 
 
a = 1           //ok
a = "hello"     //ok
a=true          //Compile error Type 'true' is not assignable to type 'string | number'

Objects

The following examples create Marks type alias and create three objects using that.

type Marks = {
  name: string;
  marks:number;
}

let marks1: Marks = { name:'Tom',marks:90 }
let marks2: Marks = { name:'Poldark',marks:75 }
let marks3: Marks = { name:'Harry',marks:80 }

Use the question mark (?) to mark the optional object members.

type Marks = {
  name: string;
  marks:number;
  pass?:boolean        //optional object members
}

let marks1: Marks = { name:'Tom',marks:90 }
let marks2: Marks = { name:'Poldark',marks:60, pass:false }
let marks3: Marks = { name:'Harry',marks:80 }

Nesting Types

TypeScript allows type aliases to be nested.

In the example below, the Type Alias Company contains the manager property which is of type Person.

type Person = {
  name: string;
};

type Company = {
  name: string;
  manager: Person;
};


let microsoft:Company = {
    name:'Microsoft',
    manager: {
        name:'Bill Gates'
    }
}

Arrays

We can create custom types for arrays. Type stringArray is an alias from array of strings.

type stringArray= string[];


let arr:stringArray=[]
arr[0]="Hello"

Tuple

The type alias can also be used to type a tuple. The Status type in the following code can contain only two elements. The first element should be a string and the second element is a boolean.

type Status = [string, boolean];
let arr: Status = ["active", true];

arr[0]="Done";    //ok
arr[0]=false;     //Type 'boolean' is not assignable to type 'string'.

arr[1]=false;
arr[1]="false";   //Type 'string' is not assignable to type 'boolean'.

arr[2]=""         //Tuple type 'Status' of length '2' has no element at index '2'.

Type Alias for Functions

We can also create a Type Alias for a function expression. The following Type alias FuncPrintString accepts a string as an argument and returns a void.

type FuncPrintString = (strToPrint:string) => void

// function expression
let printMe:FuncPrintString = function(foo) {
  console.log(foo)
}

printMe(1)  //Argument of type 'number' is not assignable to parameter of type 'string'.
printMe("Hello")  //ok

But there is no option to apply a type alias to a function declaration.

type FuncPrintString = (strToPrint:string) => void

// function declaration. Cannot apply type alias here
function printMe(foo) {
  console.log(foo)
}

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top