TypeScript Type Guards
🛡️ TypeScript Type Guards (Beginner → Advanced)
Type Guards in TypeScript are techniques that help the compiler narrow down types within a block of code.
They are essential for working with union types, APIs, and real-world applications like React & Node.js.
1️⃣ What Are Type Guards?
A type guard is an expression or function that performs a runtime check to guarantee the type of a variable.
✔ Safer code
✔ Fewer runtime errors
✔ Better IntelliSense
2️⃣ typeof Type Guard ⭐ (Primitive Types)
Used for primitive types.
✔ Works with: string, number, boolean, bigint, symbol, undefined, function
3️⃣ instanceof Type Guard ⭐ (Classes)
Used with class instances.
✔ Works only with classes, not interfaces
4️⃣ in Operator Type Guard ⭐
Checks if a property exists in an object.
✔ Very useful for object unions
5️⃣ Discriminated (Tagged) Unions ⭐⭐
A powerful and recommended pattern.
✔ Clean
✔ Safe
✔ Exhaustive
6️⃣ Custom Type Guards (is) ⭐⭐
Define your own type guard functions.
✔ Extremely powerful
✔ Common in enterprise code
7️⃣ Type Guards with unknown ⭐
✔ Required before using unknown
8️⃣ Exhaustiveness Checking with never 🔥
✔ Ensures all cases handled
✔ Great for refactoring safety
9️⃣ Type Guards in Arrays ⭐
✔ Useful for API data cleanup
🔟 Common Mistakes ❌
-
Using
anyinstead of guards -
Forgetting to narrow
unknown -
Using
instanceofwith interfaces -
Overusing type assertions (
as)
📌 Interview Questions (Must Prepare)
-
What is a type guard?
-
Difference between
typeofandinstanceof -
What is a custom type guard?
-
What is a discriminated union?
-
Why is
neverused in guards? -
How to narrow
unknown?
🔥 Real-World Use Cases
-
API response validation
-
Form handling
-
Redux reducers
-
Event handlers
-
Library design
✅ Summary
✔ Type guards narrow union types safely
✔ Built-in: typeof, instanceof, in
✔ Discriminated unions are best practice
✔ Custom guards provide maximum control
✔ Essential for TypeScript mastery & interviews
