Lesson 37 of 60 – Union Types
62%

Union Types in TypeScript

A union type allows a variable, property, or function parameter to accept more than one type. Union types are created using the pipe | operator.

Note: Use a union type when a value can legitimately be one of several different types.

1. What is a Union Type?

A union type allows a value to have more than one possible type.

let id: number | string;

id = 101;

id = "ST101";

Here, id can contain either a number or a string.

2. Union Type Syntax

The basic syntax is:

type1 | type2

Example:

let value: string | number;

The pipe symbol | means "or" in a union type.

3. String or Number

One of the most common union types allows either a string or a number.

let value: string | number;

value = "Hello";

value = 100;

4. String or Boolean

A union can contain a string and a boolean.

let result: string | boolean;

result = "Success";

result = true;

5. Number or Boolean

A value can also be either a number or a boolean.

let value: number | boolean;

value = 100;

value = false;

6. Multiple Types in a Union

A union can contain more than two types.

let value:
    string |
    number |
    boolean;

value = "Hello";

value = 100;

value = true;

7. Union Type with Variable

Union types can be used when declaring variables.

let studentId: number | string;

studentId = 101;

console.log(studentId);

studentId = "ST101";

console.log(studentId);

8. Union Type with Function Parameter

Function parameters can accept multiple types.

function printId(
    id: number | string
) {
    console.log(id);
}

printId(101);

printId("ST101");

9. Union Type with Function Return Value

A function can return more than one possible type.

function getValue(
    condition: boolean
): string | number {

    if (condition) {
        return "Success";
    }

    return 100;
}

console.log(
    getValue(true)
);

console.log(
    getValue(false)
);

10. Union Types in Interface Properties

Interface properties can use union types.

interface Student {
    id: number | string;
    name: string;
}

const student: Student = {
    id: 101,
    name: "Amit"
};

The id property can contain either a number or a string.

11. Changing Between Union Types

A variable with a union type can receive different allowed types.

let id: number | string;

id = 101;

id = "ST101";

id = 202;

Each assignment must match one of the types in the union.

12. Invalid Value in Union

Values outside the union are not allowed.

let id: number | string;

id = 101;

id = "ST101";

// id = true; // Error

Boolean is not part of the declared union.

13. Union Type with Arrays

A variable can contain either a string array or a number array.

let data: string[] | number[];

data = [
    "HTML",
    "CSS"
];

data = [
    10,
    20,
    30
];

14. Array Containing Multiple Types

There is an important difference between a union of arrays and an array containing union values.

let values: (string | number)[] = [
    "Amit",
    100,
    "Rahul",
    200
];

Here, individual array elements can be either strings or numbers.

15. Union Types with Literal Values

Union types can restrict a variable to specific values.

let status:
    "pending" |
    "approved" |
    "rejected";

status = "pending";

status = "approved";

Only the specified values are allowed.

16. Union Type for User Roles

Union types are useful for fixed categories such as user roles.

let role:
    "admin" |
    "student" |
    "teacher";

role = "admin";

role = "teacher";

17. Union Type and typeof

When a value has multiple possible types, use typeof to determine its current type.

function showValue(
    value: string | number
) {

    if (typeof value === "string") {
        console.log(
            value.toUpperCase()
        );
    }

    if (typeof value === "number") {
        console.log(
            value.toFixed(2)
        );
    }
}

showValue("hello");

showValue(100);

18. Type Narrowing with Union

Type narrowing means reducing a union to a more specific type before performing type-specific operations.

function display(
    value: string | number
) {

    if (typeof value === "string") {

        console.log(
            "String:",
            value
        );

    } else {

        console.log(
            "Number:",
            value
        );

    }
}

19. Union with null

A union can explicitly allow null.

let username:
    string | null;

username = "Amit";

username = null;

This is useful when a value may not currently exist.

20. Union with undefined

A union can also allow undefined.

let phone:
    string | undefined;

phone = "9876543210";

phone = undefined;

21. Union with null and undefined

let value:
    string |
    null |
    undefined;

value = "Hello";

value = null;

value = undefined;

All three values are allowed because they are included in the union.

22. Union Types with Objects

A union can contain different object structures.

interface Admin {
    name: string;
    role: "admin";
}

interface Student {
    name: string;
    role: "student";
}

let user:
    Admin | Student;

user = {
    name: "Amit",
    role: "admin"
};

user = {
    name: "Rahul",
    role: "student"
};

23. Discriminated Union

A common property can be used to distinguish between different object types.

interface Admin {
    role: "admin";
    name: string;
}

interface Student {
    role: "student";
    name: string;
}

type User =
    Admin | Student;

function showUser(
    user: User
) {

    if (user.role === "admin") {
        console.log(
            "Admin:",
            user.name
        );
    } else {
        console.log(
            "Student:",
            user.name
        );
    }
}

24. Union Types in React Props

Union types can be used for React component properties.

interface ButtonProps {
    title: string;
    size: "small" | "medium" | "large";
}

function Button(
    props: ButtonProps
) {

    return (
        <button>
            {props.title}
        </button>
    );
}

The size property accepts only the specified values.

25. Union Types in React Native

React Native components can use union types for properties such as button variants or display modes.

interface ButtonProps {
    title: string;
    variant:
        "primary" |
        "secondary" |
        "danger";
}

const Button = (
    props: ButtonProps
) => {

    return (
        <View>
            <Text>
                {props.title}
            </Text>
        </View>
    );
};

26. Union Types for API Responses

API responses can sometimes have different possible states. A union can describe these states.

interface SuccessResponse {
    status: "success";
    data: string;
}

interface ErrorResponse {
    status: "error";
    message: string;
}

type ApiResponse =
    SuccessResponse |
    ErrorResponse;

27. Common Union Type Mistake

A common mistake is trying to use an operation that is not available on every type in the union.

function printValue(
    value: string | number
) {

    // value.toUpperCase();
    // Error because number
    // does not have toUpperCase()

}

Narrow the type before using a type-specific method.

28. When Should You Use Union Types?

Union types are useful when a value can legitimately have different possible types or values.

  • ID can be a number or string.
  • A status can have specific values.
  • An API response can have different states.
  • A React prop can accept specific variants.
  • A value can be string, number, or boolean.
  • A value can be an object of different defined shapes.

29. Complete Practical Example

interface Student {
    type: "student";
    id: number | string;
    name: string;
    course: string;
}

interface Teacher {
    type: "teacher";
    id: number | string;
    name: string;
    subject: string;
}

type User =
    Student | Teacher;

function showUser(
    user: User
) {

    console.log(
        "Name:",
        user.name
    );

    console.log(
        "ID:",
        user.id
    );

    if (user.type === "student") {

        console.log(
            "Course:",
            user.course
        );

    } else {

        console.log(
            "Subject:",
            user.subject
        );

    }
}

showUser({
    type: "student",
    id: 101,
    name: "Amit",
    course: "TypeScript"
});

showUser({
    type: "teacher",
    id: "T101",
    name: "Rahul",
    subject: "JavaScript"
});

30. Union Types Summary

Union types allow a value to belong to one of several specified types.

let value:
    string |
    number;

value = "Hello";

value = 100;

Use the | operator to create unions and use type narrowing when you need to perform operations specific to one member of the union.

📌 Key Points

  • Union types allow multiple possible types.
  • Use the | operator to create a union.
  • A union can contain two or more types.
  • Union types can be used with variables and properties.
  • Function parameters and return types can use unions.
  • Union types can contain literal values.
  • Union types can include null and undefined.
  • Arrays can use union types.
  • Object structures can be combined using unions.
  • Use type narrowing when working with different members of a union.
  • Discriminated unions are useful for related object structures.
  • Union types are commonly used in React and React Native applications.

🧠 Quick Quiz

Question: Which symbol is used to create a union type in TypeScript?