Lesson overview · Free interview practice

Type Guards

Implement custom type guards and narrowing.

Topics in the full lesson
  • Introduction to Type Guards and Type Narrowing
  • Understanding Type Guards
  • User-Defined Type Guards
  • Type Narrowing
  • Discriminated Unions
  • Exhaustiveness Checking
  • Advanced Type Guards
  • Best Practices
  • Exercises

Try the free interview questions

Work through a question before revealing its explanation. These questions and answers are free; Premium adds the full lesson walkthrough, examples and implementation detail.

TheoryEasy

Narrowing with the `in` Operator

Question

How does the in operator narrow types in TypeScript? When does it win over discriminated unions?

Take a moment to think about this before revealing the answer

Explain your reasoning or try an implementation before comparing answers.

TheoryMedium

Type Guards vs Type Assertions

Question

What's the difference between a type guard and a type assertion? When is each one safe to use?

Take a moment to think about this before revealing the answer

Explain your reasoning or try an implementation before comparing answers.

TheoryMedium

Assertion Functions: `asserts x is T`

Question

What is an assertion function in TypeScript? When does the asserts predicate fit better than a regular is type guard?

Take a moment to think about this before revealing the answer

Explain your reasoning or try an implementation before comparing answers.

TheoryMedium

Discriminated Unions: The Tagged Variant Pattern

Question

What is a discriminated union, and how does TS narrow it? Show the canonical exhaustive-switch pattern.

Take a moment to think about this before revealing the answer

Explain your reasoning or try an implementation before comparing answers.

TheoryMedium

User-Defined Type Guards with the `is` Predicate

Question

How do you write a custom type guard with the is predicate? Why does it narrow the type, and what's the lying-guard footgun?

Take a moment to think about this before revealing the answer

Explain your reasoning or try an implementation before comparing answers.

Explore the full Type Guards material

Premium includes the complete lessons and implementation references. Free practice questions remain available without a subscription.

All course tracks & premium content
From basics to advanced masterclasses
Built for JS/TS developers like you
Real-world tips & common pitfalls
Upgrade to Premium