Understanding Union Types in TypeScript
Discover TypeScript union types, which allow a variable or function parameter to hold multiple data types. Learn how to use union types to enhance flexibility in your code and handle different data types effectively.
>
TypeScript Unions
A union type in TypeScript represents a value that can be one of several types. This flexibility is useful when a variable or function parameter can hold different data types.
Syntax:
Syntax
let value: Type1 | Type2 | ... | TypeN;
Creating and Using Unions
Example
let result: number | string;
result = 42; // Valid
result = "Hello"; // Valid
// result = true; // Error: Type 'boolean' is not assignable to type 'number | string'
Unions in Function Parameters
Example
function processValue(value: string | number) {
if (typeof value === 'string') {
console.log(`Got a string: ${value}`);
} else if (typeof value === 'number') {
console.log(`Got a number: ${value}`);
}
}
Type Narrowing with Unions
When working with unions, it's often necessary to narrow down the type based on conditions. TypeScript's type narrowing allows you to safely access properties or methods specific to a particular type within the union.
Example
function processValue(value: string | number | boolean) {
if (typeof value === 'string') {
console.log(value.length); // Accessing string-specific property
} else if (typeof value === 'number') {
console.log(value.toFixed(2)); // Accessing number-specific method
} else {
console.log(value);
}
}
Common Use Cases
- Optional Parameters:
(param?: string | undefined)
- Function Return Types:
(): number | string
- Discriminated Unions: Complex object structures with a type discriminator property
Cautions and Best Practices
- While unions provide flexibility, overuse can lead to less type safety.
- Use type guards or discriminated unions to safely access properties or methods based on the actual type.
- Consider creating custom types or interfaces for complex union scenarios.
By understanding and effectively using TypeScript unions, you can write more flexible and adaptable code.
>