TypeScriptInterview preparation
Intermediate·Concept·2 min read

How do narrowing and type guards work?

Practice this question

Definition:

Narrowing is TypeScript's process of reducing a broad type to a more specific type based on control flow and checks. A type guard is a check that gives the compiler evidence about a value, such as typeof, in or a custom predicate. Correct guards help application code safely use data that starts out uncertain.

Key points:

  • A check like typeof value === 'string' narrows the type.

  • A custom guard can return value is User after checking required fields.

  • A type assertion like as User does not validate anything.

  • A custom predicate must really check the claimed shape; TypeScript trusts the predicate's return type.

  • Check for null before using object properties, because runtime typeof null is "object".

Example:

TypeScript
function display(value: unknown): string {
  if (typeof value === 'string') return value.toUpperCase();
  if (typeof value === 'number') return value.toFixed(2);
  return 'Unsupported value';
}
  • The checks narrow unknown before type-specific methods are used.

Interview point:

  • A type assertion asks the compiler to trust you; a type guard supplies a check that can protect the running program.
Adapted from 01_JAVASCRIPT_TYPESCRIPT.md · “How do narrowing and type guards work?”. Code examples are study fragments. Difficulty and core labels are editorial estimates; version-specific behavior should be checked against your project.