TypeScript - Union Type

Type Script History

Quite commonly in JavaScript you want to allow a property to be one of multiple types e.g. string or a number. This is where the union type (denoted by | in a type annotation e.g. string|number) comes in handy. A common use case is a function that can take a single object or an array of the object e.g.:

  

        (type1 | type2 | type3 | .. | typeN)
    

Example

  

        let code: (string | number);
        code = 123;   // OK
        code = "XYZ"; // OK
        code = false; // Compiler Error

        let empId: string | number;
        empId = 111; // OK
        empId = "E111"; // OK
        empId = true; // Compiler Error
    

Function Parameter as Union Type

  

        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);