How Do Union Types Work in TypeScript?

Learn How Do Union Types Work in TypeScript? with practical examples, explanations, best practices, and real-world coding techniques.

Introduction to Union Types

In JavaScript, a variable can hold values of different types at different points during execution. TypeScript adds static type checking to help you control which values are valid and how they can be used.

A union type allows a value to belong to one of several permitted types. You create a union by separating the alternatives with the pipe symbol, |. For example, string | number means that a value can be either a string or a number.

Union types are useful when a function accepts different input formats, an API returns different kinds of results, a value can represent several states, or an application supports a fixed set of valid options. TypeScript checks that values belong to the declared alternatives and requires you to narrow the type before performing operations that are not valid for every alternative.

1. Creating a Basic Union Type

A union type combines two or more types into one accepted type. The value must satisfy at least one of the alternatives.

let identifier: string | number;

identifier = "USER-101";
console.log(identifier);

identifier = 101;
console.log(identifier);

// Compile-time error:
// identifier = true;

The identifier variable accepts strings and numbers because both alternatives are declared. Assigning a boolean is rejected because boolean is not part of the union.

A union does not mean that a variable holds all listed types simultaneously. Its value at a particular moment must be compatible with at least one alternative. In this example, identifier contains either a string or a number.

You can use unions with local variables, function parameters, return types, object properties, array elements, and type aliases. They are particularly valuable when a single concept legitimately supports several representations.

2. Using Type Aliases for Union Types

When a union is used repeatedly, define a type alias to give it a meaningful name. This makes function signatures easier to understand and allows the same set of alternatives to be reused consistently.

type UserId = string | number;

type InputValue = string | number | boolean;

let userId: UserId = 101;
let input: InputValue = "Hello";

userId = "USR-202";
input = true;

function findUser(id: UserId): string {
  return "Looking up user: " + id;
}

console.log(findUser(userId));
console.log(input);

UserId represents identifiers that can be either strings or numbers. InputValue represents values that can be strings, numbers, or booleans.

A type alias does not create a new runtime type or validate incoming values. It gives an existing type expression a reusable name for static checking.

Prefer meaningful aliases when a union represents a domain concept, such as UserId, InputValue, or PaymentMethod, instead of repeating long type expressions throughout the application.

3. Working with Union Types Safely

When a value has a union type, TypeScript generally permits operations that are valid for every possible alternative. An operation that works only for one alternative requires type narrowing first.

function printValue(value: string | number): void {
  console.log(value);

  // Compile-time error:
  // console.log(value.toUpperCase());
}

printValue("TypeScript");
printValue(100);

The value parameter can be either a string or a number. The toUpperCase method belongs to strings, so TypeScript cannot allow that call without additional evidence that value is a string.

This behavior prevents code from relying on methods that might not exist for the actual runtime value. It encourages you to check which alternative is present before using alternative-specific operations.

You can narrow a union using typeof checks, equality comparisons, the in operator, instanceof, and checks of a shared discriminant property. These techniques provide increasingly useful ways to work with different kinds of values.

4. Narrowing Union Types with typeof

The typeof operator reports a value's JavaScript type category. TypeScript understands many typeof checks and uses them to narrow a union within the corresponding conditional branch.

function formatValue(value: string | number): string {
  if (typeof value === "string") {
    return value.toUpperCase();
  }

  return value.toFixed(2);
}

console.log(formatValue("typescript"));
console.log(formatValue(42.5));

Inside the first branch, TypeScript knows that value is a string, so toUpperCase is available. After that branch returns, the remaining possibility is a number, allowing toFixed to be called.

This pattern is commonly called type narrowing. TypeScript starts with a broader set of possible types and uses control flow to determine which alternatives remain possible at a particular location.

Be aware that typeof null returns "object" in JavaScript. If a union includes null, you should handle that possibility explicitly rather than relying on typeof alone to identify a non-null object.

5. Literal Union Types

Union types can contain specific literal values instead of entire types. A literal union restricts a value to a clearly defined set of strings, numbers, booleans, or other supported literal types.

type Theme = "light" | "dark" | "system";

type HttpStatus = 200 | 400 | 404 | 500;

let selectedTheme: Theme = "dark";
let statusCode: HttpStatus = 200;

selectedTheme = "light";
statusCode = 404;

// Compile-time errors:
// selectedTheme = "blue";
// statusCode = 201;

console.log(selectedTheme);
console.log(statusCode);

Theme permits only light, dark, or system. HttpStatus permits only the declared numeric values.

Literal unions are especially useful for configuration options, application states, sorting directions, button variants, supported languages, and workflow steps.

They prevent invalid values from being assigned accidentally. For example, a function that accepts Theme does not accept "blue" unless that value is added to the type.

Literal union types improve editor autocomplete and make application contracts easier to understand. However, they do not validate values received from external sources at runtime; such values still need suitable validation before being trusted.

6. Narrowing with Equality Checks

Equality checks can narrow unions that contain literal alternatives. This is useful when a value has a small number of expected states or known identifiers.

type PaymentStatus =
  | "pending"
  | "completed"
  | "failed";

function getPaymentMessage(status: PaymentStatus): string {
  if (status === "completed") {
    return "Payment successful";
  }

  if (status === "failed") {
    return "Payment unsuccessful";
  }

  return "Payment is being processed";
}

console.log(getPaymentMessage("completed"));
console.log(getPaymentMessage("pending"));

Each equality comparison narrows status to a specific literal value. After the completed and failed conditions return, the remaining valid alternative is pending.

This is more reliable than treating status as an arbitrary string because TypeScript checks that callers provide one of the supported states.

Equality-based narrowing also works with null checks, boolean literals, and comparisons between compatible union alternatives. Use it when a condition clearly identifies one of the declared possibilities.

7. Union Types with Objects

Union types become more powerful when they describe alternative object structures. A variable can represent one object shape or another, depending on the application's requirements.

type EmailNotification = {
  email: string;
  subject: string;
};

type SmsNotification = {
  phone: string;
  message: string;
};

type Notification =
  | EmailNotification
  | SmsNotification;

const emailNotice: Notification = {
  email: "asha@example.com",
  subject: "Welcome"
};

const smsNotice: Notification = {
  phone: "+910000000000",
  message: "Your code is 1234"
};

console.log(emailNotice);
console.log(smsNotice);

Notification allows either an email notification or an SMS notification. Each object must satisfy one of the declared alternatives.

When accessing a property that exists on only one alternative, check which alternative is present first. For example, emailNotice.email is available for its inferred EmailNotification type, while a variable declared as Notification does not automatically have an email property.

Union object types are useful when modeling different authentication methods, API response shapes, payment methods, user roles, and other concepts that can take several forms.

8. Discriminated Union Types

A discriminated union is a union of object types that share a common property with different literal values. This property, commonly called a discriminant, lets TypeScript identify which object variant is being handled.

type SuccessResult = {
  status: "success";
  data: string;
};

type ErrorResult = {
  status: "error";
  message: string;
};

type ApiResult = SuccessResult | ErrorResult;

function displayResult(result: ApiResult): string {
  if (result.status === "success") {
    return "Data: " + result.data;
  }

  return "Error: " + result.message;
}

console.log(
  displayResult({
    status: "success",
    data: "Course loaded"
  })
);

console.log(
  displayResult({
    status: "error",
    message: "Course not found"
  })
);

Both object types contain a status property, but its literal type differs. When status is success, TypeScript narrows result to SuccessResult and permits access to data. When status is error, it narrows the value to ErrorResult and permits access to message.

The discriminant eliminates ambiguity and avoids unsafe property access. It also makes the individual cases easy to understand when reading the code.

Discriminated unions are an excellent choice for API results, loading states, form states, asynchronous operations, and event payloads. They provide a clear relationship between a state identifier and the properties available in that state.

9. Exhaustive Checking with never

The never type represents values that cannot occur at a particular point in a correctly checked program. With discriminated unions, it can help verify that every alternative has been handled.

type Shape =
  | { kind: "circle"; radius: number }
  | { kind: "rectangle"; width: number; height: number };

function assertNever(value: never): never {
  throw new Error("Unexpected value: " + value);
}

function getArea(shape: Shape): number {
  switch (shape.kind) {
    case "circle":
      return Math.PI * shape.radius * shape.radius;

    case "rectangle":
      return shape.width * shape.height;

    default:
      return assertNever(shape);
  }
}

console.log(getArea({ kind: "circle", radius: 5 }));
console.log(
  getArea({ kind: "rectangle", width: 4, height: 6 })
);

After both Shape variants have been handled, TypeScript knows that shape should be never in the default branch. Passing it to assertNever therefore succeeds.

If you later add another shape variant without adding a corresponding switch case, the default branch will receive that unhandled variant instead of never. TypeScript reports an error, helping you identify the missing case during development.

Exhaustive checking is particularly valuable when unions describe business workflows or application states that must be handled completely. It makes future changes easier to maintain because new alternatives trigger relevant type errors.

10. Union Types in Arrays

Union types can describe an array whose elements may have different types. The placement of parentheses changes the meaning, so distinguish between an array of union values and a union of array types.

const mixedValues: (string | number)[] = [
  "TypeScript",
  100,
  "JavaScript",
  200
];

const namesOrIds: string[] | number[] = [
  101,
  102,
  103
];

console.log(mixedValues);
console.log(namesOrIds);

The type (string | number)[] permits each array element to be a string or a number. The array can contain both types at the same time.

By contrast, string[] | number[] means that the value is either an array containing strings or an array containing numbers. It does not describe one array whose elements freely alternate between the two types.

Choose the first form for mixed collections, such as rows containing labels and numeric identifiers. Choose the second when the entire collection should use one element type, but the permitted element type can differ between arrays.

11. Union Types in Function Parameters and Returns

Function parameters and return values can both use unions. A union parameter allows callers to provide different input types, while a union return type communicates that the function may return different kinds of values.

function normalizeId(id: string | number): string {
  return String(id).trim();
}

function findValue(key: string): string | undefined {
  const values: Record<string, string> = {
    theme: "dark",
    language: "English"
  };

  return values[key];
}

console.log(normalizeId(101));
console.log(normalizeId(" USER-202 "));
console.log(findValue("theme"));
console.log(findValue("unknown"));

normalizeId accepts either a string or a number and consistently returns a string. The String conversion works with both alternatives, so no separate narrowing is necessary.

findValue returns string | undefined because a requested dictionary entry might be missing. The union makes that possibility part of the function's contract, encouraging callers to handle an absent result instead of assuming every lookup succeeds.

Union return types should accurately describe all possible outcomes. If a function may return an error object, a value, or no result, choose a type that represents those possibilities clearly rather than hiding them behind a broad type such as any.

12. Union Types vs Intersection Types

Union types and intersection types solve different problems. A union uses the pipe symbol to allow one of several alternatives. An intersection uses the ampersand symbol to combine requirements from multiple types.

type Admin = {
  name: string;
  permissions: string[];
};

type Member = {
  name: string;
  membershipLevel: number;
};

type User = Admin | Member;

type AdminMember = Admin & Member;

const user: User = {
  name: "Asha",
  permissions: ["manage-courses"]
};

const combined: AdminMember = {
  name: "Rahul",
  permissions: ["manage-courses"],
  membershipLevel: 2
};

console.log(user.name);
console.log(combined.membershipLevel);

User accepts an Admin or a Member. A value only needs to satisfy one alternative to be assignable, although it may contain members from both.

AdminMember combines both requirements. A value must provide the properties required by both Admin and Member.

Use unions when a concept can take different forms. Use intersections when a value must satisfy several compatible contracts at once. Intersections of conflicting property types can produce difficult or impossible-to-satisfy types, so ensure the combined requirements are compatible.

Common Mistakes with Union Types

Using a union without narrowing

A union value cannot safely use methods that exist on only one alternative until TypeScript can determine which alternative is present. Narrow the value with a suitable check.

Confusing arrays of unions with unions of arrays

(string | number)[] permits mixed elements. string[] | number[] describes an array whose element type is consistently one alternative.

Using general types instead of literal unions

A string type accepts arbitrary strings. A union such as "light" | "dark" restricts the value to supported choices and makes configuration mistakes easier to catch.

Creating ambiguous object unions

If alternative object types do not have a reliable way to distinguish them, property access and branching can become difficult. A shared discriminant property with distinct literal values usually creates a clearer design.

Forgetting to handle every alternative

A newly added union member can make existing logic incomplete. Use exhaustive switch statements with never when every variant must be handled.

Assuming types validate external data

Union annotations do not check actual API responses at runtime. Validate external values before treating them as one of the declared alternatives.

Best Practices for Union Types

  • Use unions when a value genuinely supports a defined set of alternatives.
  • Create descriptive type aliases for unions reused across multiple functions or components.
  • Use literal unions to restrict configuration values and application states to valid options.
  • Narrow unions before accessing members or methods that are not shared by every alternative.
  • Prefer discriminated unions for related object variants with different properties or behaviors.
  • Use exhaustive checking with never when every union alternative must be handled.
  • Pay attention to parentheses when declaring arrays that contain several possible element types.
  • Choose intersection types instead when all combined requirements must be satisfied simultaneously.
  • Return explicit and accurate union types when functions can produce several expected outcomes.
  • Validate untrusted runtime values rather than assuming TypeScript annotations enforce external data contracts.

Conclusion

Union types allow TypeScript values to represent multiple permitted alternatives without losing static type checking. They support flexible variables, function inputs, return types, collections, literal options, and alternative object structures.

Type narrowing is what makes these alternatives safe to use. Checks such as typeof, equality comparisons, and discriminant properties help TypeScript identify the active alternative. For complex object unions, exhaustive checking with never helps keep application logic complete as requirements change.

Practise defining simple unions, narrowing them in conditional branches, modeling API results with discriminated unions, and handling all possible outcomes. With these patterns, you can represent real application behavior precisely while keeping your code easier to maintain.

Code Examples

Basic Union Type

typescript
let identifier: string | number;

identifier = "USER-101";
console.log(identifier);

identifier = 101;
console.log(identifier);

// Compile-time error:
// identifier = true;
    

The union permits identifier to hold either a string or a number. TypeScript rejects values that do not belong to either alternative.

Narrowing a Union with typeof

typescript
function formatValue(value: string | number): string {
  if (typeof value === "string") {
    return value.toUpperCase();
  }

  return value.toFixed(2);
}

console.log(formatValue("typescript"));
console.log(formatValue(42.5));
    

The typeof check narrows value to string in the first branch and number in the remaining branch, allowing each alternative to use its appropriate operation.

Literal Union Type

typescript
type Theme = "light" | "dark" | "system";

function setTheme(theme: Theme): string {
  return "Selected theme: " + theme;
}

console.log(setTheme("dark"));
console.log(setTheme("system"));

// Compile-time error:
// setTheme("blue");
    

A literal union restricts the accepted values to a specific set of strings, improving autocomplete and preventing unsupported configuration choices.

Discriminated Union for API Results

typescript
type ApiResult =
  | { status: "success"; data: string }
  | { status: "error"; message: string };

function displayResult(result: ApiResult): string {
  if (result.status === "success") {
    return "Data: " + result.data;
  }

  return "Error: " + result.message;
}

console.log(displayResult({
  status: "success",
  data: "Course loaded"
}));

console.log(displayResult({
  status: "error",
  message: "Course not found"
}));
    

The shared status property distinguishes the object variants, allowing TypeScript to safely expose data or message in the corresponding branch.

Exhaustive Checking with never

typescript
type Shape =
  | { kind: "circle"; radius: number }
  | { kind: "rectangle"; width: number; height: number };

function assertNever(value: never): never {
  throw new Error("Unexpected value: " + value);
}

function getArea(shape: Shape): number {
  switch (shape.kind) {
    case "circle":
      return Math.PI * shape.radius * shape.radius;

    case "rectangle":
      return shape.width * shape.height;

    default:
      return assertNever(shape);
  }
}

console.log(getArea({ kind: "circle", radius: 5 }));
    

The never check ensures that every declared Shape variant is handled. Adding a new variant without updating the switch creates a compile-time error.

Union Arrays vs Union of Arrays

typescript
const mixedValues: (string | number)[] = [
  "TypeScript",
  100,
  "JavaScript",
  200
];

const names: string[] | number[] = ["Asha", "Rahul"];
const ids: string[] | number[] = [101, 102];

console.log(mixedValues);
console.log(names);
console.log(ids);
    

An array of union values can mix strings and numbers in one collection. A union of arrays represents a value that is either a string array or a number array.

Pro Tip

Use literal unions for values with a fixed set of valid choices and discriminated unions for alternative object shapes. Narrow a union before using variant-specific properties, and use never to catch missing cases in exhaustive switches. Remember that union types provide compile-time guarantees, not runtime validation of external data.

More TypeScript lessons

🎨 IgKnight Docs

Master HTML, CSS, JS, Python, .NET and more with easy-to-follow lessons and practical code examples.

© 2025 IgKnight Learning Platform. All rights reserved.