Mid-level (2-5 years)TypeScript

What is type narrowing in TypeScript?

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.

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.

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);
}