Skip to lesson

TypeScript · Lesson 15 of 42

Union types: a value that can be one of several types

Learn union types such as string | number, which members you can use before narrowing, and how unions model optional and nullable values.

Beginner to advanced·13 min·Combining and narrowing types·Updated 2026-11-24

UNDERSTAND IT. THEN TRY IT.

What you can do after this lesson

You will be able to say "this value is one of these several types", which real data often is. A form field might be a string or empty, an ID might be a number or a string, and a result might be a success or a failure. Unions describe all of these, and they are the foundation for the next three lessons.

The | operator

A union type is written with a vertical bar between types and means "either this or that":

typescript
let id: string | number;

id = "A-17";
console.log(id);

id = 17;
console.log(id);
result
A-17
17

The variable can hold either kind, one at a time. Anything else is rejected:

typescript
let id: string | number;
id = true;
result
example.ts(2,1): error TS2322: Type 'boolean' is not assignable to type 'string | number'.

What you can do with a union

Here is the important rule: until you narrow a union, you may only use members that every type in the union has. A number has no toUpperCase, so this fails:

typescript
function shout(value: string | number): string {
  return value.toUpperCase();
}
result
example.ts(2,16): error TS2339: Property 'toUpperCase' does not exist on type 'string | number'.
  Property 'toUpperCase' does not exist on type 'number'.

The message explains it in two lines: the property is missing on string | number, because it is missing on number. The fix is to check which type you have, and use only what that type supports. The next lesson, on narrowing, covers the tools for this:

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

console.log(shout("hello"), shout(42));
result
HELLO 42.0

Members shared by all types are always available. Both strings and arrays have length, so a union of the two can use it directly:

typescript
function size(value: string | string[]): number {
  return value.length;
}

console.log(size("hello"), size(["a", "b"]));
result
5 2

Unions of literal types

You met this idea with type aliases. A union of literal types gives a closed set of options:

typescript
type Size = "small" | "medium" | "large";

function price(size: Size): number {
  if (size === "small") return 3;
  if (size === "medium") return 4;
  return 5;
}

console.log(price("medium"));
result
4

Optional and nullable values

A union with undefined or null describes a value that may be missing. This is the type behind optional properties and functions that sometimes find nothing:

typescript
function findUser(id: number): string | undefined {
  const users: Record<number, string> = { 1: "Asha", 2: "Ben" };
  return users[id];
}

const user = findUser(3);
console.log(user === undefined ? "not found" : user.toUpperCase());
result
not found

With strict mode, the compiler forces you to check for undefined before using the result. That single rule prevents a huge class of "cannot read properties of undefined" errors.

Array of unions versus union of arrays

These two look similar and mean different things:

typescript
const mixed: (string | number)[] = [1, "two", 3];
const onlyStrings: string[] | number[] = ["a", "b"];

console.log(mixed, onlyStrings);
result
[ 1, 'two', 3 ] [ 'a', 'b' ]

(string | number)[] is one array whose items may each be a string or a number. string[] | number[] is either an array of only strings or an array of only numbers. The parentheses matter, so write them when you mean a mixed array.

Unions in return types

A function can return different types on different paths, and the compiler infers the union. Writing the return type yourself keeps the intent clear:

typescript
function parseAge(input: string): number | null {
  const age = Number(input);
  return Number.isNaN(age) ? null : age;
}

console.log(parseAge("42"), parseAge("forty"));
result
42 null

Callers now know the result may be null, and the compiler makes them handle it.

Common mistakes

Calling a method that only some members have. Narrow first. A union exposes only what all members share.

Forgetting the parentheses in an array of unions. string | number[] means a string or an array of numbers, not an array of mixed items.

Using a union where one precise type will do. If a function always receives a string, do not accept string | undefined just in case.

Ignoring null and undefined. In strict mode they are in the type for a reason; check them before use.

Exercise

Write function formatId(id: string | number): string that returns "ID-" followed by the id, padding numbers to four digits with padStart. Write findIndexOf(items: string[], target: string): number | null that returns null when the item is missing, and use the result safely. Finally, make an array that mixes numbers and strings, and try to call toFixed on its first item to see why narrowing is needed.

Next: Narrowing with typeof, truthiness and equality checks.

KNOWLEDGE CHECK

A quick check. You’ve got this.

Try each question. Every answer comes with an explanation.

0 / 4 understood
01 What does let id: string | number allow?
02 Why does value.toUpperCase() fail when value has type string | number?
03 Which type allows an array that mixes strings and numbers?
04 How do you say a value may be a string or may be missing?

Ready for the next small win?

Mark the lesson complete when you are ready.

Course navigation

Frontend

TypeScript tutorial

Add types to JavaScript to catch mistakes before your code runs, from your first annotation to generics and real projects.

Your progress 0/42
Learning something new?Explore all courses