1. Concept library
  2. JavaScript & TypeScript
  3. Module 3: Objects, interfaces, unions

Concept

Union types

A | B means a value that is one of several types. Unions model real choices, such as a result that is a number or an error, without resorting to any.

What a session covers

The tutor works through these with you, in conversation and code. A session ends when you have shown them, not when a video does.

  1. Explain what a union type means and give a case where it models a real choice
  2. Write a function that takes string | number and narrows before using each member
  3. Spot the error from calling a method only one member of the union has

In practice

A few lines that show Union types doing its job.

TypeScript
type Id = string | number;

function normalise(id: Id): string {
  return typeof id === "number" ? String(id) : id.trim();
}

type Loaded = { data: string[] } | { error: string };
function show(state: Loaded) {
  if ("error" in state) return state.error;
  return state.data.length + " items";
}

The common mistake

Watch for

Calling a method that only one member of the union has, before narrowing. On string | number, .trim() is an error until a typeof check has ruled out the number.

What to know first

Your roadmap puts these before Union types, unless you already know them.

How it stays learned

Once a session shows you understand Union types, it comes back for review. Each review takes a minute and tells the memory model how well you still know it.

  1. Day 3First recall, while it is fresh
  2. Day 7Second, a week on
  3. Day 18Last, when it has settled

Where it leads

Topics that build on Union types.

Previous in the module← Interfaces and type aliases
Next in the moduleLiteral types →