
Ts Union Types in TypeScript
A union type in TypeScript allows a variable to hold one of several defined types. It provides flexibility while still maintaining type safety, making it especially useful for scenarios where a value can have multiple types.
Syntax
Union types are defined using the pipe (|
) symbol between two or more types.
// value = true; // Error: Type 'boolean' is not assignable to type 'string | number'
Features of Union Types
Type Safety
TypeScript ensures that only the specified types are allowed.Flexibility
Enables handling of values with varying types in a controlled manner.Type Narrowing
Use type guards to determine the specific type of a union variable.
Examples of Union Types
1. Basic Union Type
let data: number | string;data = 10; // Validdata = "Ten"; // Valid
2. Union in Function Parameters
function printValue(value: string | number): printValue(42); // Output: 42
Type Guards
TypeScript allows you to narrow down the type of a union variable using conditional checks.
Using typeof
function processValue(value: string | number): void { if (typeof value === "string") { console.log(value.toUpperCase()); // Works because 'value' is narrowed to string } else { console.log(value.toFixed(2)); // Works because 'value' is narrowed to number }}
Using instanceof
class Dog { bark() { console.log("Woof!"); }}class Cat { meow() { console.log("Meow!"); }}function handlePet(pet: Dog | Cat): void { if (pet instanceof Dog) { pet.bark(); } else { pet.meow(); }}
Union with Arrays
Union types can be used for arrays to allow elements of different types.
let mixedArray: (number | string)[] = [1, "two", 3, "four"];
Union with Literal Types
Union types can include literal values for more specific constraints.
type Direction = "up" | "down" | "left" | "right";function move(direction: Direction): void { console.log(`Moving ${direction}`);}move("up"); // Valid// move("forward"); // Error: Type '"forward"' is not assignable to type 'Direction'
Union with Null or Undefined
Union types are commonly used to handle null
or undefined
values, especially when strictNullChecks
is enabled.
let name: string | null = null;name = "Alice"; // Valid
Advantages of Union Types
Improves Code Flexibility
Handles multiple input types in a single variable or parameter.Enhances Code Safety
Prevents runtime errors by enforcing compile-time checks for allowed types.Clearer Code Intentions
Makes it explicit that a variable or parameter can have more than one type.
Common Use Cases
Function Overloads
function getLength(value: string | string[]): number { return typeof value === "string" ? value.length : value.length;}
Error Handling
type Response = { success: true; data: string } | { success: false; error: string };function handleResponse(response: Response): void { if (response.success) { console.log("Data:", response.data); } else { console.error("Error:", response.error); }}
API Parameters
type ID = number | string;function fetchUser(id: ID): void { console.log(`Fetching user with ID: ${id}`);}
Best Practices
Use Type Guards for Narrowing
Always check the specific type before performing type-specific operations.Combine with Aliases
Usetype
aliases to simplify complex union types.type Input = string | number;
Avoid Overuse
If a union becomes too complex, consider refactoring with interfaces or discriminated unions.
Conclusion
Union types are a powerful feature in TypeScript that allow for flexible yet type-safe handling of variables with multiple possible types. By leveraging union types effectively, you can write robust and maintainable code.