Open In App

What is the use of Union Type in TypeScript ?

The union type in TypeScript is used to define the variables with multiple data types. It allows a variable to store the values of different data types in it. It is specified by defining the multiple types separated using a straight vertical line (|).

A union type is mainly is to define an array to make it store the values of multiple data types inside it. It is very important to have an array that can store the values of multiple data types in languages like TypeScript.



Syntax:

const variable_name: (type1 | type2 | type3) = value_of_any_specified_type;

Example: The below code will help you understand the use of the union type in TypeScript.




const array: (number | string | boolean)[] =
    [1, 2, "GFG", false, "TypeScript"];
console.log(array);

Output:



[1, 2, "GFG", false, "TypeScript"]
Article Tags :