Type narrowing in TypeScript
Let the compiler prove what a value is, instead of casting your way past it.
Narrowing is how TypeScript turns a wide type into a specific one inside a branch.
Discriminated unions#
type Result = { ok: true; value: number } | { ok: false; error: string };
function unwrap(r: Result) {
if (r.ok) return r.value; // narrowed to the first member
throw new Error(r.error); // narrowed to the second
}