What is Union in TypeScript
What is Union in TypeScript?
Union in TypeScript allows creating types that can be one of several types. This means a variable or function parameter can have multiple possible data types. Union helps make code more flexible by providing the ability to work with multiple data types simultaneously.
Union Syntax
Union types are created using the | (or) operator. It allows specifying multiple types to choose from.
Example:
let value: string | number;
value = "Hello"; // Valid
value = 42; // Valid
value = true; // Error, as type is neither string nor number
In this example, the value variable can be either a string or a number. If you assign a value of another type, TypeScript will throw an error.
Recommendation:
Use Union types to create flexible and safe data types when a variable or function can work with multiple types.