In TypeScript, it is possible to declare a variable that can hold various types of values. This means TypeScript is capable of merging one or more distinct data types (such as number, string, etc.) into a single type known as a union type. Union types provide a robust method for representing a variable that can encompass multiple types. To combine two or more data types, the pipe ('|') symbol is utilized between the types.
Syntax
(type1 | type2 | type3 | ........ | type-n)
Example
let value: number|string;
value = 120;
console.log("The Numeric value of a value is: "+value);
value = "Welcome to TypeScript Tutorial";
console.log("The String value of a value is: "+value);
Output:
The Numeric value of the value is: 120
The String value of the value is: Welcome to TypeScript Tutorial
Passing Union Type in Function Parameter
In a function, it is possible to pass a union type as an argument. This can be illustrated by the example provided below.
Example
function display(value: (number | string))
{
if(typeof(value) === "number")
console.log('The given value is of type number.');
else if(typeof(value) === "string")
console.log('The given value is of type string.');
}
display(123);
display("ABC");
Output:
The given value is of type number.
The given value is of type of string.
Passing Union Type to Arrays
TypeScript permits the inclusion of a union type within an array. This can be illustrated through the following example.
Example
let arrType:number[]|string[];
let i:number;
arrType = [1,2,3,4];
console.log("Numeric type array:")
for(i = 0;i<arrType.length;i++){
console.log(arrType[i]);
}
arrType = ["India","America","England"];
console.log("String type array:")
for(i = 0;i<arrType.length;i++){
console.log(arrType[i]);
}
Output:
Numeric type array:
1
2
3
4
String type array:
India
America
England
The union can replace enums.
Enums serve the purpose of defining types that encompass a collection of constants. Typically, enums are assigned index values starting from zero (0, 1, 2, 3, etc.). An illustration of enums can be observed in the subsequent example, which presents a compilation of colors.
Example
export enum Color {RED, BLUE, WHITE}
Rather than utilizing enums, we can implement union types to achieve comparable advantages in a more concise manner.
Example
export type Color = 'red' | 'white' | 'blue';
const myColor: Color = 'red';
console.log(myColor.toUpperCase());
Output: