Close

TypeScript - Type Aliases

[Last Updated: Oct 28, 2018]

TypeScript allows to create reuseable aliases for a simple, intersection, unions, tuples or any other valid TypeScript types.

To declare an alias we need to use the following syntax:

type myTypeName = <a valid TypeScript type>

Examples

Simple types

type chars = string;
function show(param: chars): void {
    console.log(param);
}
show("hello");

Output

hello

Union types

type num = number | string;
function square(n: num): number {
    if (typeof n === 'string') {
        n = parseInt(n);
    }
    return Math.pow(n, 2);
}
console.log(square(3));
console.log(square("5"));

Output

9
25

Object properties/function/array types

//object properties
type Product = { name: string, price: number };
let p: Product = {price: 100, name: 'Monitor'};
console.log(p);
//function
type StringRemover = (input: string, index: number) => string;
let remover: StringRemover = function (str: string, i: number): string {
    return str.substring(i);
}
let s = remover("Hi there", 3);
console.log(s);
//array
type State = [string, boolean];
let a: State = ["active", true];
console.log(a);

Output

{ price: 100, name: 'Monitor' }
there
[ 'active', true ]

Using Literals

We we declare aliases with union types and a number of literal values to get enum-like behavior:

type Alignment = "Left" | "RIGHT" | "CENTER";
function doAlign(alignment: Alignment):void{
    console.log(alignment);
}
doAlign("Left");//should be one of the above three values (case sensitive)

type WIDTH = 100 | 200 | 300;
function setWidth(w: WIDTH){
    console.log(w);
}
setWidth(100);//should be one of the above three numbers

Output

Left
100

Example Project

Dependencies and Technologies Used:

  • TypeScript 3.1.3
TypeScript - Type Aliases Select All Download
  • typescript-type-aliases
    • type-alias-example.ts

    See Also