Concept
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.
The tutor works through these with you, in conversation and code. A session ends when you have shown them, not when a video does.
A few lines that show Union types doing its job.
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";
}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.
Your roadmap puts these before Union types, unless you already know them.
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.
Topics that build on Union types.