Horje
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.

Javascript

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

Output:

[1, 2, "GFG", false, "TypeScript"]



Reffered: https://www.geeksforgeeks.org


JavaScript

Related
How to implement Type narrowing in TypeScript? How to implement Type narrowing in TypeScript?
JavaScript Program to Search an Element in an Array JavaScript Program to Search an Element in an Array
How to Declare an Array in JavaScript ? How to Declare an Array in JavaScript ?
What is Callback Hell in JavaScript ? What is Callback Hell in JavaScript ?
Pass by Value in JavaScript Pass by Value in JavaScript

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
13