Type Guards and Narrowing
Prerequisites: Union types, any/unknown/never
Narrowing is TypeScript refining a union type to one specific possibility, based on a runtime check you've already written.
function printLength(value: string | string[]) {
if (typeof value === "string") {
console.log(value.length); // narrowed to string
} else {
console.log(value.length); // narrowed to string[]
}
}
typeof, instanceof, and in are the most common type guards.
Once you've checked a condition, TypeScript remembers it for the rest
of that code branch — no extra syntax needed beyond the check itself.