TypeScript Union Type

TypeScript Union Type is a hint of possible data types of a variable. We used union types when we are not sure about the possible variable data type but we know about possible data types are limited.

For example we have a variable discount. We know a discount variable is always be a number data type. But we are using external JavaScript libraries and that libraries can send discount value in a string data type. So we created a single union type variable which takes both a number and a string value. Below is the example:

function calculateDiscount(discount: number | string) {
}

calculateDiscount(11);

calculateDiscount("15");

In calculateDiscount function we have a parameter discount which takes both number and string datatypes.

Union Type Syntax

A union type possible data types are separated by pipe symbol (|). Below is the example:

var isArticlePublished: boolean | number;

We have a colon (:) after the variable name and then possible data types of isArticlePublished variable separated by pipe symbol.

Union Type with Array

A Union type can be used with array data types. Below is the 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 of array types with union types. Below is the example:

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

In the above example, we have to check whether itemsToSort variable is a number array or a string array. To check we have to check the first item in a array whether it is a number or string. Below is the 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 above example, first condition check whether itemsToSort is null or not then check it's first item is null or not and then check whether first item in an array is number or not. If first item is a number then it is a number array. Same condition is check in elseif but with check whether first item is string or not.

Summary

Union type is a special data type with a hint of possible data types of a variable. We can assign all type of values specified in union data types. We can determine variable using the 'typeof' operator.

Join our newsletter and get an occasional email with a technology and DotNetPattern.com news update.