Master TypeScript From Scratch

Learn TypeScript step by step with practical examples, interactive coding lessons, and real-world projects.

TypeScript Union Types

Learn how to allow a variable, parameter or property to accept values from multiple types using the union operator.

Simple Explanation: A union type allows a value to be one of several specified types. TypeScript uses the pipe symbol (|) to define a union.

1. What is a Union Type?

A union type combines two or more possible types into one type. The value can match any one of the specified types.

For example, a student ID might be stored as either a number or a string. A union type can represent both possibilities.

Basic Syntax

let studentId: string | number;

studentId = 101;
console.log(studentId);

studentId = "STU102";
console.log(studentId);

Expected Output

101
STU102

The variable studentId can hold either a string or a number. A boolean value would not be valid for this union type.

2. Union Types Workflow Diagram

Follow this diagram to understand how TypeScript checks values against the possible types in a union.

📝
Define Union

Specify the allowed types using the pipe symbol.

→
📥
Receive Value

Assign or receive a value that matches one of the types.

→
🔍
Check Type

Use type narrowing when a specific type is needed.

→
✅
Use Value

Perform operations supported by the narrowed type.

Remember: A union permits multiple types, but you can only access operations that are valid for the current narrowed type or safe for every member of the union.

3. Union of String and Number

One common use of union types is to allow the same variable or function parameter to accept strings and numbers.

Example

type Identifier = string | number;

function displayId(id: Identifier): void {
    console.log("ID: " + id);
}

displayId(101);
displayId("EMP102");

Expected Output

ID: 101
ID: EMP102

The Identifier type alias names the union. The function accepts either a number or a string without requiring separate functions.

4. Union of Multiple Types

A union can contain more than two types. Each value must match at least one of the types listed in the union.

Example

let value: string | number | boolean;

value = "TypeScript";
console.log(value);

value = 100;
console.log(value);

value = true;
console.log(value);

Expected Output

TypeScript
100
true

Allowed Values

🔤
String

Example: "TypeScript"

🔢
Number

Example: 100

✅
Boolean

Example: true

Note: Only the specified types are allowed. An object or array, for example, would not be accepted by this union unless its type were included.

5. Type Narrowing with typeof

When a value belongs to multiple possible types, TypeScript may not know which type it currently has. Type narrowing helps identify the type before performing a type-specific operation.

The typeof operator is commonly used to distinguish primitive types such as strings and numbers.

Example

function displayValue(value: string | number): void {
    if (typeof value === "string") {
        console.log(value.toUpperCase());
    } else {
        console.log(value * 2);
    }
}

displayValue("hello");
displayValue(10);

Expected Output

HELLO
20

How Type Narrowing Works

📥
Union Value

Receives a string or a number.

→
🔍
typeof Check

Checks whether the value is a string.

→
🔤
String Branch

Uses toUpperCase() for string values.

→
🔢
Number Branch

Performs multiplication for numeric values.

Key Point: Inside each branch, TypeScript narrows the type so you can use operations that are appropriate for that type.

6. Literal Union Types

A literal union restricts a value to a specific set of allowed values. It is especially helpful for statuses, categories, roles and application settings.

Example: Order Status

type OrderStatus = "Pending" | "Shipped" | "Delivered";

function updateStatus(status: OrderStatus): void {
    console.log("Order Status: " + status);
}

updateStatus("Pending");
updateStatus("Shipped");
updateStatus("Delivered");

// This would cause a TypeScript error:
// updateStatus("Cancelled");

Expected Output

Order Status: Pending
Order Status: Shipped
Order Status: Delivered

The OrderStatus type only permits the three specified strings. Other strings, such as "Cancelled", are not valid for this type.

7. Union Types with Objects

A union can describe a value that may be one of multiple object structures. A property shared by both structures can be accessed directly. To access a property unique to one structure, first narrow the type.

Example

type Student = {
    name: string;
    course: string;
};

type Teacher = {
    name: string;
    subject: string;
};

function displayPerson(person: Student | Teacher): void {
    console.log("Name: " + person.name);

    if ("course" in person) {
        console.log("Course: " + person.course);
    } else {
        console.log("Subject: " + person.subject);
    }
}

displayPerson({
    name: "Rahul",
    course: "TypeScript"
});

displayPerson({
    name: "Priya",
    subject: "Programming"
});

Expected Output

Name: Rahul
Course: TypeScript
Name: Priya
Subject: Programming

Object Union Diagram

👨‍🎓
Student

name

course

👩‍🏫
Teacher

name

subject

🔀
Student | Teacher

Check which object structure is present before accessing a unique property.

Both object types contain name, so it can be accessed directly. The course and subject properties require narrowing.

8. Union Types in Arrays

You can define an array whose elements may be strings or numbers. Parentheses around the union clarify that the union is the array's element type.

Example

const values: (string | number)[] = [
    "Rahul",
    101,
    "Priya",
    102
];

values.forEach(value => {
    console.log(value);
});

Expected Output

Rahul
101
Priya
102

Each element in values can be a string or a number. Other types, such as booleans, are not accepted by this array type.

9. Common Mistakes in Union Types

Mistake Correct Approach
Assigning a value outside the union. Use one of the types declared in the union.
Calling a string-only method on a possible number. Use type narrowing such as typeof first.
Accessing a property unique to one object type. Use a property check such as "course" in person.
Using a broad string instead of specific allowed statuses. Use a literal union such as "Pending" | "Delivered".
Assuming TypeScript types validate external input at runtime. Use runtime validation for API responses and other external data.

Summary

Union types use the | operator to allow values from multiple types. They work with primitive types, literal values, objects and arrays. Type narrowing using typeof or property checks helps TypeScript identify which operations are safe for the current value.

Next, learn Intersection Types and how to combine multiple type requirements into a single type.