What is type narrowing in TypeScript?

Answer

Type narrowing is the process of refining a broader type (like a union) to a more specific type within a conditional block. TypeScript uses control flow analysis to track which types are possible at each point in the code. Common narrowing techniques: typeof guard: if (typeof value === "string") { value.toUpperCase(); }. instanceof guard: if (error instanceof TypeError) { ... }. Truthiness narrowing: if (value) { /* value is not null/undefined/falsy */ }. Equality narrowing: if (x === "hello") { /* x is "hello" */ }. in operator: if ("swim" in animal) { animal.swim(); }. Discriminated unions: a common literal property used to differentiate union members. Custom type guards: functions with a value is Type return type. After narrowing, TypeScript knows the exact type and provides full type checking and autocomplete for that specific type's members.