LESSON 05 / 6·2 min readIntermediate

How do narrowing and type guards work?

Try code in the playground
01 Understand02 Recall03 Prepare

Understand the concept

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.

Important ideas

  • 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".

Work through the 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.
PAUSE & RECALL

Can you explain it without the notes?

How do narrowing and type guards work?

Use your own words. Explain an example and one limitation before checking the explanation.

Check your explanation

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.

CONNECT IT TO YOUR INTERVIEW

Turn this concept into a clear answer.

  • A type assertion asks the compiler to trust you; a type guard supplies a check that can protect the running program.
Practice this concept
YOUR NEXT STEP

Keep connecting the ideas.

Next lesson: What are mapped types, conditional types and decorators?

Adapted from 01_JAVASCRIPT_TYPESCRIPT.md · “How do narrowing and type guards work?”. Examples are study fragments; framework behavior can depend on your version.