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.

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

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

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 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.

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.

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

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

Objects

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

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

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.

Arrays

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

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 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.

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

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