TypeScript Union Type

TypeScript Union Type is a hint to the compiler for possible data types for a variable. We use the union data type when we are not sure about the possible variable data types, but we know that the possible data types are limited.

For example, we have a function named “calculateDiscount” that calculates the discount on the price item. A user can pass discount data in both number and string formats. To handle this scenario, we can give instructions to the typescript compiler by using the union type, where the discount variable can be of the number or string data type. Below is an example:

function calculateDiscount(discount: number | string) {
    if (typeof discount === 'number') {
        console.log('Discount variable is in number format.')
    }
    else if (typeof discount === 'string') {
        console.log('Discount variable is in string format.')
    }
}

calculateDiscount(10);
calculateDiscount("12");

In the calculateDiscount function, we have a parameter discount that takes both number and string datatypes.

Union Type Syntax

A pipe symbol (|) is used to separate the possible data types of the union type. Below is an example:

var isArticlePublished: boolean | number;

First, we declare a variable named isArticlePublished; after that, we define two data types, boolean and number, which are separated by a pipe symbol.

Union Type with Array

A union type can be used with array data types. Below is an example:

var itemsToSort: number[] | string[];

itemsToSort = [5, 3, 2, 1, 4];
itemsToSort = ["5", "3", "2", "1", "4"];

A itemsToSort data type can take both an array of numbers and an array of string data types.

Union Array Type Check

By default, TypeScript does not provide type checking for array types with union types. Below is an example:

function bubbleSort(itemsToSort: number[] | string[]) {
    //write code to sort
}

In the above example, we have to check whether the itemsToSort variable is a number array or a string array. To check, we have to check the first item type in an array, whether it is a number or a string. Below is an example:

function bubbleSort(itemsToSort: number[] | string[]) {
    if (itemsToSort && itemsToSort[0] && (typeof itemsToSort[0] === "number")) {
        console.log('number array');
    }
    else if (itemsToSort && itemsToSort[0] && typeof itemsToSort[0] === "string") {
        console.log('string array');
    }
    else {
        console.log('undefined');
        return;
    }
    //write code to sort
}

bubbleSort([3, 2, 1, 4, 5]);
bubbleSort(["3", "2", "1", "4", "5"]);

In the above example, the first condition is to check whether the “itemsToSort” variable is null or not, then check whether the first item is null or not, and then check whether the first item in an array is a number or not. If the first item is a number, then it is a number array. The same condition is checked in the else if statement about whether the first item is a string or not for checking the string array.

Summary

A union type is a special data type with a hint of possible data types for a variable. We can assign all types of values specified in union data types. We can determine variables using the ‘typeof’ operator.