MediumConcept

What is type narrowing in TypeScript?

Technology:
TypeScript
Experience:
Mid-level,
Senior

Quick answer

Narrowing is when TypeScript shrinks a wide type (such as a union) to a more specific type after a runtime check like typeof, instanceof, in, or a custom type guard.

Detailed explanation

Control-flow analysis follows your if and switch. typeof x === "string" narrows string | number to string in that branch. x instanceof Date works for classes. "width" in value distinguishes object shapes. A user-defined guard is a function whose return type is value is Fish.

Equality checks against a discriminant (event.type === "click") are the cleanest pattern for API payloads. Assertions (value as User) skip narrowing and are a common source of production bugs: the compiler believes you, the runtime does not.

Example

typescript
function isUser(value: unknown): value is { id: string } {
  return typeof value === "object" && value !== null && "id" in value;
}

function label(value: string | number) {
  return typeof value === "string" ? value.toUpperCase() : value.toFixed(2);
}
  • TypeScriptMedium

    What are generics in TypeScript?

    Generics are type parameters: they let a function, class or type work with many types while keeping the relationship between inputs and outputs, instead of falling back to any.

    Junior 路 Mid-level 路 Types & Type System
  • TypeScriptMedium

    What are utility types in TypeScript like Partial, Pick and Omit?

    Utility types are built-in helpers that transform an existing type: Partial makes every field optional, Required the opposite, Pick keeps a set of keys, Omit removes them, and Record builds a key/value map.

    Junior 路 Mid-level 路 Types & Type System
  • TypeScriptMedium

    What is the difference between enum and union types in TypeScript?

    A string union such as "admin" | "user" exists only in the type system and erases to plain strings. A TypeScript enum compiles to a JavaScript object (unless it is a const enum), which is extra runtime code and a weaker default.

    Mid-level 路 Senior 路 Types & Type System
  • TypeScriptMedium

    How does TypeScript type inference work?

    TypeScript fills in types you omit: literals get their literal or widened type, function return types are inferred from return statements, and generic arguments are inferred from the values you pass.

    Mid-level 路 Senior 路 Types & Type System