Close

TypeScript - Union Types

[Last Updated: Oct 26, 2018]

In TypeScript, a union type allows to use multiple types choices.

The type any allows all type to be used, whereas, union types restrict that scope by providing specific types.

Example

function square(x: number | string): number {
    if (typeof x == 'string') {
        let a = parseInt(x)
        if (isNaN(a)) {
            throw Error("x is not a number: " + x);
        }
        x = a;
    }
    return Math.pow(x, 2);
}

let result = square("4");
console.log(result);
result = square(5);
console.log(result);

Output

16
25

In above example if we use 'any' instead, then the caller can pass a type other than 'string' or 'number':

function square(x: any): number {
    if (typeof x == 'string') {
        let a = parseInt(x)
        if (isNaN(a)) {
            throw Error("x is not a number: " + x);
        }
        x = a;
    }
    return Math.pow(x, 2);
}

let result = square({a: 4});
console.log(result);

Output

NaN

Example Project

Dependencies and Technologies Used:

  • TypeScript 3.1.3
TypeScript - Union Types Select All Download
  • typescript-union-type
    • union-type-example.ts

    See Also