Skip to content
Tutorials Center
My learning

Topics

Lesson 15 of 96 ยท Basic Types

Union Types

Learn TypeScript union types - writing A | B, what you can do with a union, narrowing with typeof and in, nullable types, literal unions and arrays of unions.

Real values are often "one of several things". An ID might be a number or a string. A function might return a user or null. A setting might be 'light', 'dark' or 'system'. In JavaScript you handle these cases with if checks and hope you didn't miss one. In TypeScript you say it in the type: number | string. That's a union type, and it's one of the most useful features in the language.

A union A | B means "a value that is an A or a B". This lesson shows how to write unions, why TypeScript limits what you can do with them, how a simple if check unlocks the specific type (a preview of Narrowing), and the difference between an array of a union and a union of arrays.

Writing a union

Put a vertical bar | between the member types. You can combine as many as you like:

TypeScript A parameter that accepts two types

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The output is #42, #a7f3, null, 21.5 and the array [ 'x', 1, true, 10n, null, undefined ]. A template literal can turn any value into text, so formatId doesn't need to know which member it got. The type Primitive = ... line gives the union a name; Type Aliases covers that in detail. The leading | before the first member is optional and only there for neat formatting.

Assignability works the way you'd expect: a number can go anywhere a number | string is expected, because it's one of the options. The reverse isn't true. A number | string can't be passed where only a number is allowed, because it might be a string.

You can only use what every member has

Here's the rule that surprises people at first. With a value of type number | string, TypeScript lets you do only the things that are valid for both numbers and strings:

TypeScript Using a member-specific method (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

TEXT
main.ts(2,16): error TS2339: Property 'toUpperCase' does not exist on type 'string | number'.
  Property 'toUpperCase' does not exist on type 'number'.
main.ts(6,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type.

The second line of the first error explains exactly why: numbers don't have toUpperCase, and value might be a number. Methods that both types share, like toString() and valueOf(), are fine to call directly. (TypeScript writes the union as string | number; the order of members never matters.)

This rule is what makes unions safe. TypeScript won't let you assume a member, so you can't forget the other case.

Narrowing: finding out which member you have

To use member-specific features, check the value at runtime. TypeScript follows your if statements and narrows the type inside each branch. This is called control-flow analysis:

TypeScript Narrowing with typeof

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

This prints QUIET PLEASE, 3.1, [ menu] and [>> menu]. After the if that returns, TypeScript knows only number remains, so the second return in each function needs no check at all.

typeof works for primitives. Other checks narrow other unions:

Check Narrows Example
typeof x === 'string' primitives string | number
x === null, x !== undefined nullable types User | null
Array.isArray(x) arrays vs. other values string | string[]
'prop' in x objects with different properties Cat | Dog
x instanceof Date class instances Date | string
x.kind === 'circle' tagged object unions Circle | Square

Narrowing explains every one of these in depth. For now, the key idea is: unions plus checks give you flexible inputs without giving up safety.

A common pattern: "one or many"

Functions often accept either a single item or an array of items. Array.isArray narrows the union cleanly:

TypeScript One value or an array of values

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The output is #typescript, #types #unions #narrowing, email [email protected] and phone 555-0100 x12.

Nullable types: T | null and T | undefined

The most common union of all is "a value or nothing". With strictNullChecks (part of --strict), null and undefined aren't hidden inside every type, so you must say when they're allowed:

TypeScript Handling a value that might be missing

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

This prints Hello, Ada ([email protected]), Hello, Grace (no email on file) and No user with id 3. If you remove the if (user === null) check, TypeScript reports error TS18047, "'user' is possibly 'null'", on user.name. That single check prevents one of the most common runtime crashes in JavaScript.

Should you use null or undefined for "nothing"? JavaScript itself uses undefined for missing properties and array lookups, and null is common in APIs and JSON. Many teams pick one style for their own functions; what matters most is that the type says it. The JavaScript lesson on null and undefined compares the two at runtime.

Unions of literal types

Union members don't have to be broad types like string. They can be exact values. A union of string literals is the TypeScript way to say "one of these specific strings", and it's often a better choice than an enum:

TypeScript
type Theme = 'light' | 'dark' | 'system';

function applyTheme(theme: Theme): void { /* ... */ }

applyTheme('dark');     // OK
applyTheme('blue');     // error TS2345: Argument of type '"blue"' is not assignable to parameter of type 'Theme'.

Editors autocomplete the three allowed values, and typos are caught instantly. The next lesson, Literal Types and as const, is all about this pattern.

Unions of object types

Unions of objects model data that comes in several shapes. The best version gives each shape a common property with a different literal value, often called kind, type or status. Checking that property narrows to one shape:

TypeScript A union of object shapes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The output lists the three payments. TypeScript even knows the switch covers every case, so the function needs no final return. This is a discriminated union, and it's how TypeScript developers model states, events, API responses and commands. You saw a taste of it in any, unknown, never and void; Discriminated Unions teaches the full pattern.

Arrays of unions vs. unions of arrays

Two types look similar but behave very differently:

  • (string | number)[] is one array where each element may be a string or a number: ['a', 1, 'b'].
  • string[] | number[] is either an array of only strings or an array of only numbers: ['a', 'b'] or [1, 2], never mixed.
TypeScript Two different array types

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The output is [ 'a', 1, 'b', 2, 3, 'c' ], 2 items: red, green, 3 items: 3, 1, 4, and 8 2. In summarize, reading methods like map, filter, forEach and length work on the union of arrays, and each element has type string | number.

Notice the limit in total: checking typeof data[0] narrows data[0], not data itself, so the loop still has to check each element. Writing to a union of arrays is even stricter:

TypeScript
function addOne(data: string[] | number[]): void {
  data.push(1);
  // error TS2345: Argument of type '1' is not assignable to parameter of type 'never'.
}

That never is TypeScript being careful: if data is a string[], pushing a number would corrupt it, and if it's a number[], pushing a string would. The only value safe for both is one that's a string and a number (string & number), and no such value exists, so the parameter type is never.

Choose by meaning. If mixing is fine, use (A | B)[]. If every element in one array must be the same kind, use A[] | B[], and usually narrow it once near the top (for example with a separate kind property describing the array).

How TypeScript infers unions

You don't always write unions yourself. TypeScript infers them when a value can come from several places:

TypeScript
const flag = Math.random() > 0.5;
const value = flag ? 'yes' : 0;          // 'yes' | 0
const items = [1, 'two', null];          // (string | number | null)[]

function parse(input: string) {
  const n = Number(input);
  return Number.isNaN(n) ? null : n;     // return type: number | null
}

Inferred unions are a good sign that you need a check later. If parse returns number | null, every caller must handle the null, exactly as the function's behavior requires. That's TypeScript turning documentation into enforced rules.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Does this compile? function f(x: string | number) { return x.length; }

    On a union you can only use members that every type in it has. Narrow with typeof x === 'string' first.
  2. 2. Inside if (typeof v === 'string') { ... } else { ... } with v: string | number | boolean, what is the type of v in the else branch?

    The typeof check removes string in the else branch, leaving number | boolean.
  3. 3. Which value is valid for string[] | number[]?

    A union of arrays means one homogeneous array, either all strings or all numbers. Mixed arrays need (string | number)[].
  4. 4. What is the inferred return type of function p(s: string) { return s ? s.length : null; }?

    The function returns a number in one branch and null in the other, so TypeScript infers the union number | null.
  5. 5. Why does data.push(1) fail when data: string[] | number[]?

    A value pushed must fit whichever array it really is, so it must be string & number, which is never.

Summary

  • A | B means a value that is an A or a B. Member order doesn't matter, and a leading | is allowed for formatting.
  • You can only use properties and methods that every member has. Checks like typeof, === null, Array.isArray, in and instanceof narrow the union inside each branch.
  • T | null and T | undefined model "maybe missing" values; strict null checks force you to handle them.
  • Unions of literals ('light' | 'dark') describe a fixed set of values; unions of object shapes with a shared tag property are discriminated unions.
  • (A | B)[] is one mixed array; A[] | B[] is one homogeneous array of either kind. Reading methods work on both, but pushing into a union of arrays expects never.
  • TypeScript infers unions from conditionals and multiple returns, a hint that callers need a check.

Next: Literal Types and as const