TYPESCRIPT
TypeScript Union: Syntax, Usage, and Examples
A TypeScript union allows a variable, function parameter, or return type to accept multiple possible types. Instead of limiting a value to a single type, unions give flexibility while maintaining type safety.
What Is a Union in TypeScript?
A union in TypeScript represents a type that can be one of several specified types. This is useful when a variable may have different kinds of values but still needs type checking.
let value: string | number;
value = "Hello";
value = 42;
In this example, value
can be either a string
or a number
. TypeScript will enforce that value
does not take any other type.
TypeScript Union vs. Enum
Both enums and unions allow handling multiple values, but they serve different purposes.
Enums define named constants that compile into JavaScript objects:
enum Status {
Pending = "PENDING",
Approved = "APPROVED",
Rejected = "REJECTED",
}
let requestStatus: Status = Status.Pending;
console.log(requestStatus); // Output: "PENDING"
Unions, on the other hand, allow variables to accept multiple specific types without generating extra JavaScript code:
type StatusUnion = "PENDING" | "APPROVED" | "REJECTED";
let requestStatus: StatusUnion = "PENDING";
console.log(requestStatus); // Output: "PENDING"
Union types are often preferable when you don’t need extra JavaScript output or when working with literal values.
How to Use TypeScript Unions
TypeScript Union Types
Union types use the |
(pipe) symbol to define multiple possible types.
function display(value: string | number) {
console.log(value);
}
display("Hello"); // Valid
display(100); // Valid
// display(true); // Error: Type 'boolean' is not assignable to type 'string | number'
TypeScript Discriminated Union
A discriminated union combines a union type with a shared property to help TypeScript infer which type is being used.
type Circle = { kind: "circle"; radius: number };
type Square = { kind: "square"; side: number };
type Shape = Circle | Square;
function getArea(shape: Shape): number {
if (shape.kind === "circle") {
return Math.PI * shape.radius ** 2;
}
return shape.side * shape.side;
}
console.log(getArea({ kind: "circle", radius: 5 })); // Output: 78.5398
console.log(getArea({ kind: "square", side: 4 })); // Output: 16
The kind
property acts as a discriminator, allowing TypeScript to narrow down the type safely.
TypeScript Union from Array
You can create a union type from an array using the as const
assertion and typeof
.
const colors = ["red", "blue", "green"] as const;
type Color = typeof colors[number];
let selectedColor: Color = "red"; // Valid
// selectedColor = "yellow"; // Error: Type '"yellow"' is not assignable to type 'Color'
This approach ensures that selectedColor
only takes values from colors
.
TypeScript Convert Union to Intersection
You can convert a union type to an intersection type using conditional types.
type A = { a: string };
type B = { b: number };
type Intersection = A & B;
const obj: Intersection = { a: "hello", b: 42 };
Intersection types require all properties from both types to be present.
TypeScript Extend Union Type
Union types can be extended by creating a new type that includes existing values and additional ones.
type BaseRole = "admin" | "user";
type ExtendedRole = BaseRole | "moderator";
let role: ExtendedRole = "moderator"; // Valid
TypeScript String Literal Union
A string literal union restricts a value to a set of predefined strings.
type Size = "small" | "medium" | "large";
function selectSize(size: Size) {
console.log(`Selected size: ${size}`);
}
selectSize("medium"); // Valid
// selectSize("extra-large"); // Error: Type '"extra-large"' is not assignable to type 'Size'
TypeScript Array to Union
To extract a union type from an array, use as const
and typeof
.
const roles = ["admin", "user", "guest"] as const;
type Role = typeof roles[number];
let userRole: Role = "admin"; // Valid
This ensures that userRole
can only hold values from roles
.
When Should You Use TypeScript Unions?
Flexible Function Parameters
Union types allow you to accept multiple types while maintaining type safety.
function formatInput(input: string | number) {
return typeof input === "number" ? input.toFixed(2) : input.toUpperCase();
}
console.log(formatInput("hello")); // Output: "HELLO"
console.log(formatInput(3.14159)); // Output: "3.14"
Handling Multiple Return Types
A function can return different types based on certain conditions.
function getValue(value: string | number): string | number {
return typeof value === "string" ? value.toUpperCase() : value * 2;
}
console.log(getValue("hello")); // Output: "HELLO"
console.log(getValue(10)); // Output: 20
TypeScript Check Type of Union
Use typeof
or discriminated unions to check the type at runtime.
function process(value: string | number) {
if (typeof value === "string") {
console.log("String:", value.toUpperCase());
} else {
console.log("Number:", value.toFixed(2));
}
}
TypeScript Cast Union Type
You can use type assertions (as
) to cast a union type.
let value: string | number = "Hello";
let stringValue = value as string;
console.log(stringValue.toUpperCase()); // Output: "HELLO"
TypeScript Check If String Is in Union Type
To check if a string belongs to a union type, use an array or object lookup.
const validSizes = ["small", "medium", "large"] as const;
function isValidSize(size: string): size is typeof validSizes[number] {
return validSizes.includes(size as any);
}
console.log(isValidSize("medium")); // Output: true
console.log(isValidSize("extra-large")); // Output: false
Learn More About TypeScript Unions
TypeScript Create Union Type from Array
To dynamically create a union type from an array, use typeof
.
const directions = ["north", "south", "east", "west"] as const;
type Direction = typeof directions[number];
TypeScript Distribute Union
TypeScript automatically distributes unions in mapped types and conditional types.
type Data<T> = T extends string ? "Text" : "Number";
type Example = Data<string | number>; // "Text" | "Number"
TypeScript Class Union
A union type can also include classes.
class Dog {
bark() {
console.log("Woof!");
}
}
class Cat {
meow() {
console.log("Meow!");
}
}
type Pet = Dog | Cat;
function makeSound(pet: Pet) {
if (pet instanceof Dog) {
pet.bark();
} else {
pet.meow();
}
}
TypeScript unions make code more flexible while maintaining type safety. They allow values to take multiple forms without losing type checking. Use unions for function parameters, return values, or data structures where multiple types are valid.
Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.