Understanding TypeScript Union Types
TypeScript Union Types
Union Types allow a variable to hold values of multiple specified types using the pipe (|) operator. The variable can only be assigned values matching the declared types.
Syntax:
type Type1 | Type2 | Type3
Basic Example
let value: string | number;
value = 12;
console.log(`Number: ${value}`);
value = "TypeScript";
console.log(`String: ${value}`);
Compiled JavaScript:
let value;
value = 12;
console.log(`Number: ${value}`);
value = "TypeScript";
console.log(`String: ${value}`);
Output:
Number: 12
String: TypeScript
Attempting to assign an invalid type causes an error:
let value: string | number;
value = true; // Type error
Function Parameters with Union Types
function display(input: string | string[]) {
if (typeof input === 'string') {
console.log(input);
} else {
input.forEach(item => console.log(item));
}
}
display("Single");
display(["Multi", "Item", "List"]);
Output:
Single
Multi
Item
List
Union Type Arrrays
let mixedArray: number[] | string[];
mixedArray = [10, 20, 30];
console.log("Numeric Array:");
mixedArray.forEach(num => console.log(num));
mixedArray = ["Apple", "Banana", "Cherry"];
console.log("String Array:");
mixedArray.forEach(str => console.log(str));
Output:
Numeric Array:
10
20
30
String Array:
Apple
Banana
Cherry