TypeScript Type Alias: Introduction and Examples

A type alias in TypeScript is used for giving new names to existing data types. Type aliases can be used with a single data type, but their primary application is with union data types, which allow a single variable to contain two or more data types. We will learn how to use TypeScript Type Alias with a variety of examples in this post.

Syntax

The TypeScript syntax for a type alias is shown below.

type variable_name = datatype | datatype | ...;

The type keyword must come before the variable name. We can list the various data types that the new data type supports after the equal sign.

Type Alias Example

For illustration, we are creating a product object. In a product object, we have three variables related to price, which can be a number, a string, or undefined.

let product {
    name: string;
    price: number | string | undefined;
    discountPrice: number | string | undefined;
    maxDiscount: number | string | undefined;
}

In this example, we need to write a number, a string, and an undefined data type for each price variable. Using type alias, we can declare these data types once and use them with every price variable, like shown below.

type money = number | string | undefined;

type product = {
    name: string;
    price: money;
    discountPrice: money;
    maxDiscount: money;
}

We have created a type alias named money, which can be a number, string, or undefined data type. We used money type alias with price, discountPrice, and maxDiscount variables of type product.

let p1: product;
p1 = {
    name: "product 1",
    price: 123.23,
    discountPrice: '10',
    maxDiscount: undefined
}

console.log(p1);

//Result
{
  "name": "product 1",
  "price": 123.23,
  "discountPrice": "10",
  "maxDiscount": undefined
}

In the above example, we have assigned different values to the money variable.

Type Alias in Function

A type alias of TypeScript can be used in a function parameter. In the below example, we have two functions that accept a parameter of the money type alias.

type money = number | string | undefined;

function calculatePrice(originalPrice: money) {

}

function calculateDiscount(price: money) {

}

calculatePrice(34.50)
calculateDiscount("12")

In both of the above functions, we accept the money parameter as a type alias that can accept a number, string, or undefined data type.

Summary

TypeScript type alias is used to give a second name to existing data types. It is mainly used with the union data type. We can also use type aliases in function parameters.

Related Posts: