Union types A | B
A union type says a value can be one type or another, written with | between the types.
A union type joins two or more types with |. Read it as "or": string | null is a value that can be a string or null.
The type checker only lets you use what works on every member of the union. To use something specific to one member, you first narrow it with a check like typeof x === "string" or x !== null. Inside that block, TypeScript knows which type you have.
In the course you see it from lesson 02.05: export let middleName: string | null = null; says the middle name may be missing, and forces whoever reads it to handle that case.
The union is type-only syntax: tsc checks it and it is gone when Node runs the code. Only the values remain at runtime.
Reach for it when: a value can legitimately have more than one shape, like data that may be missing (`string | null`) or an input that arrives as text or a number.
Examples
Common mistake
function shout(name: string | null): string {
return name.toUpperCase();
}
console.log(shout("ann"));Why: `name` may be null, and null has no `.toUpperCase()`. TypeScript stops you before it fails at runtime.
How to write it: Narrow first: if (name === null) return ""; and then use name.toUpperCase().
Common mistake
let age: string | number = 30; age = true; console.log(age);
Why: The union only admits the listed types. `boolean` is neither string nor number.
How to write it: Use a value of a listed type, or add the missing one: string | number | boolean.
