TypeScript: Type Alias – to avoid duplicate type definitions

To avoid duplication or repeated type definitions, we have the type alias in TypeScript. We can do this easily using the type keyword in TypeScript.

There are many occasions in which we have similar kinds of type definitions. In such cases, we can make use of the alias feature in TypeScript that helps to define once and use any number of times.

Let understand TypeScript type alia using an example,

TypeScript : Type Alias – Example code

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

let person : Person;       //one person

let people : Person[];     // array of persons

Here in the above given example we have defined a type alias using the type keyword provided by TypeScript. It has an object with properties of types string and number for name and age respectively.

We have made use of that type definition twice.

  • In the first case its a person variable to store data of a single person.
  • Second is people variable to store data of list of person having same properties name and age.

This is how we can make use of the type alias feature in TypeScript to avoid repeated type definitions. Also, it greatly helps to reduce the code.

About the Author: smartcoder

You might like

Leave a Reply

Your email address will not be published.