TS Union Types
Union types in TypeScript allow you to define a variable that can hold values of multiple types. This is useful for scenarios where a value could logically belong to one of several types.
Key Topics
Defining Union Types
Union types are defined using the |
operator to specify that a value can belong to multiple types.
let value: string | number;
value = "Hello, TypeScript!";
console.log(value); // Hello, TypeScript!
value = 42;
console.log(value); // 42
Output
Hello, TypeScript!
42
Explanation: The variable value
is defined with a union type string | number
, allowing it to hold either a string or a number.
Type Narrowing
Type narrowing allows you to refine the type of a union using conditional checks, ensuring type safety during operations.
function processValue(value: string | number): void {
if (typeof value === "string") {
console.log("String length:", value.length);
} else {
console.log("Squared value:", value * value);
}
}
processValue("Hello"); // String length: 5
processValue(4); // Squared value: 16
Output
String length: 5
Squared value: 16
Explanation: The typeof
operator checks the runtime type of value
, enabling safe operations based on its type.
Union Types with Arrays
Union types can also be applied to arrays, allowing them to hold elements of different types.
let mixedArray: (string | number)[] = ["Alice", 25, "Bob", 30];
for (const element of mixedArray) {
console.log(element);
}
Output
Alice
25
Bob
30
Explanation: The mixedArray
contains elements of both string
and number
types, enabling flexible and type-safe operations.
Key Takeaways
- Flexibility: Union types allow variables to hold values of multiple types.
- Type Narrowing: Use conditional checks like
typeof
to safely handle union types. - Arrays: Apply union types to arrays for mixed-type collections.
- Best Practice: Use unions to model values that logically belong to multiple types.