Union and literal types

Topic 1 of 5 in Unions and narrowing7 min readIntermediateFree course

Overview

Real data often comes in several forms: an ID that’s a string or a number, a setting that’s one of three values, a result that’s either data or an error. Union types describe “one of these”, and literal types describe exact values. Together they’re one of TypeScript’s most powerful — and most used — features.

Union and literal types. A union is “one of these types”: id: string | number accepts a string or a number. Literal types allow exact values only: size: “sm” | “md” | “lg”. let size: “sm” | “md” | “lg” = “md”; is fine, but size = “xl” is an error: Type ‘“xl”’ is not assignable to type ‘“sm” | “md” | “lg”’. With a union you can only use what every member supports — until you narrow it.

Union types

Join types with |:

TypeScript
let id: string | number;
id = "a-42";   // ✓
id = 42;       // ✓
id = true;
// error TS2322: Type 'boolean' is not assignable to type 'string | number'.

Unions work anywhere a type goes:

TypeScript
function show(value: string | string[]) { … }
type Result = Data | Error;
const items: (string | number)[] = [1, "two"];   // brackets matter: an array of either

You can only use what they share

If a value might be a string or a number, TypeScript only lets you do things that work for both:

TypeScript
function format(id: string | number) {
  id.toString();        // ✓ both have toString
  id.toUpperCase();
  // error TS2339: Property 'toUpperCase' does not exist on type 'string | number'.
  //   Property 'toUpperCase' does not exist on type 'number'.
}

That’s exactly right: if id were a number, toUpperCase would crash. To use string-only methods, first check that it is a string:

TypeScript
function format(id: string | number): string {
  if (typeof id === "string") {
    return id.toUpperCase();      // here id: string
  }
  return id.toFixed(0);           // here id: number
}

This is narrowing: TypeScript follows your check and knows which member of the union you have in each branch. Type narrowing covers every way to narrow.

Literal types

A literal type is a type with exactly one value:

TypeScript
let direction: "left" = "left";
direction = "right";
// error TS2322: Type '"right"' is not assignable to type '"left"'.

On their own they’re not very useful. Combined into a union, they describe a fixed set of options:

TypeScript
type Size = "sm" | "md" | "lg";
type Direction = "up" | "down" | "left" | "right";
type HttpMethod = "GET" | "POST" | "PUT" | "DELETE";
type DiceRoll = 1 | 2 | 3 | 4 | 5 | 6;
type Toggle = true | false;    // that's just boolean

What you get:

  • Typos are compile errors: "lg " or "large" won’t pass.
  • Autocomplete offers the options as you type the opening quote.
  • Self-documenting signatures: resize(size: Size) tells callers exactly what’s allowed — no need to read the code or docs.
  • Narrowing works on each option: after if (size === "sm") return …, TypeScript knows size is "md" | "lg".

When literal types get widened

TypeScript
type Size = "sm" | "md" | "lg";
function padding(size: Size) { … }

let s = "sm";          // let s: string — widened!
padding(s);
// error TS2345: Argument of type 'string' is not assignable to parameter of type 'Size'.

const t = "sm";        // const t: "sm"
padding(t);            // ✓

A let can be reassigned to any string, so TypeScript widens its type to string, which is too wide for Size. Fixes: use const, annotate (let s: Size = "sm"), or use as const for objects and arrays (as const and satisfies).

Unions of object types

Unions aren’t just for primitives:

TypeScript
type Cat = { name: string; meow(): void };
type Dog = { name: string; bark(): void };

function call(pet: Cat | Dog) {
  console.log(pet.name);   // ✓ both have name
  pet.meow();
  // error TS2339: Property 'meow' does not exist on type 'Cat | Dog'.
}

Telling object types apart is the job of the in operator, custom type guards and — best of all — discriminated unions, which get their own lesson.

Unions vs overloads vs generics

You now have three tools for flexible functions:

  • Union parameter — the function accepts several types and returns the same kind of thing either way: formatId(id: string | number): string.
  • Overloads — the return type depends on which type came in (Parameters and overloads).
  • Generics — the output type follows the input type exactly (Generic functions).

Reach for the union first; it’s the simplest.

Literal unions instead of magic strings

A lot of JavaScript code passes around “magic strings”: setStatus("actve") — oops. Every time you see a parameter that only accepts a few specific values, give it a literal union. It costs one line and eliminates a whole category of bugs.

Remember: | means “one of these”; literal types pin values down exactly; and you must narrow a union before using anything that only some members have.

Exercise

A button style picker

Define type Size = "sm" | "md" | "lg" and type Variant = "primary" | "secondary" | "danger". Write padding(size: Size): string returning "4px 8px", "8px 16px" or "12px 24px". Write buttonClass(variant: Variant, size: Size = "md", disabled = false): string returning e.g. "btn btn-danger btn-lg", with is-disabled added when disabled. Write formatId(id: string | number): string that pads numbers to 6 digits (42 → "000042") and upper-cases strings. Print a few results, and show with // @ts-expect-error that buttonClass("warning") and padding("xl") are rejected.

TypeScript
type Size = "sm" | "md" | "lg";
type Variant = "primary" | "secondary" | "danger";

// padding()

// buttonClass()

// formatId()

Summary

  • A union type A | B accepts a value of either type.
  • Literal types allow exact values: "sm" | "md" | "lg" is a precise, self-documenting set of options.
  • With a union, you can only use what every member supports — narrow it first to use the rest.
  • Comparing with === or checking typeof narrows a union inside that branch.
  • Literal unions replace magic strings and most enums: typos become compile errors and the editor autocompletes the options.