Type Narrowing

Noun · Development

Definitions

  1. A type system feature where the compiler refines a variable's type to a more specific one within a conditional branch — for example, after an `if (typeof x === 'string')` check in TypeScript, the compiler knows `x` is a `string` inside that block, not the wider `string | number` it was before. This eliminates the need for explicit casts in guarded code paths.

    In plain English: When the compiler automatically figures out a more specific type for a variable based on a condition you checked, like an if-statement.

    Example: "After the `instanceof` check, TypeScript narrows the union to just the Error type, so I can access `.message` without a cast."

Related Terms