Understanding TypeScript Union Types - A Comprehensive Guide
A TypeScript union describes a value that can have one of several types. Use it for values that accept more than one shape.
What are Union Types?
A union type is a type that represents a variable that can hold one of several possible types. For example, suppose you have a function that can accept a string or a number as an argument:
function printValue(value: string | number) {
console.log(value);
}
In this example, value can hold either a string or a number type. This is useful when you need a variable to hold multiple types of values.
Union types are denoted using the | (pipe) symbol. You can use as many | symbols as you need to create a union of multiple types.
Union Types with Interfaces
Union types can also be used in combination with interfaces. For example, suppose each person has both a name and an age:
interface Person {
name: string;
age: number;
}
To require either a name or an age, define a union of object types:
type Person = { name: string; age?: never } | { name?: never; age: number };
Each variant has one required property. name is a string and age is a number.
Union Types with Type Aliases
Union types can also be defined using type aliases. Type aliases are a way to create a new name for an existing type. For example, suppose you have a union type that represents a string or a number:
type StringOrNumber = string | number;
In this example, StringOrNumber is a type alias that represents a union type of string or number. You can use StringOrNumber anywhere you would use a regular string or number type.
Union Types with Generics
Union types can also be used in combination with generics. Generics are a way to create reusable code that can work with a variety of types. For example, suppose you have a function that returns either a string or a number:
function getValue<T>(value: T): T {
return value;
}
In this example, the getValue function is a generic function that can accept any type of argument and return the same type of argument. You can use this function with union types:
const stringValue = getValue<string>("hello");
const numberValue = getValue<number>(42);
const unionValue = getValue<string | number>("hello");
In this example, stringValue is of type string, numberValue is of type number, and unionValue is of type string | number.
Conclusion
Union types let a value have one of several types. Narrow the value before using operations specific to one member of the union.