Type Narrowing & GuardsBeginner
1Question 1 of 1
typescriptHow does Type Narrowing and Custom Type Guards work in TypeScript?
Explanation & Concept
Type Narrowing is TypeScript's ability to refine a variable from a broader type to a more specific type using control flow analysis (`typeof`, `instanceof`, `'prop' in obj`).
A **Custom Type Guard** is a function whose return type is a type predicate (`param is Type`), allowing runtime logic to safely narrow types in the compiler.
Code Example
typescript
interface Dog {
bark(): void;
}
interface Fish {
swim(): void;
}
// Custom Type Guard with type predicate 'pet is Fish'
function isFish(pet: Dog | Fish): pet is Fish {
return (pet as Fish).swim !== undefined;
}
function handlePet(pet: Dog | Fish) {
if (isFish(pet)) {
pet.swim(); // TypeScript knows 'pet' is definitely Fish
} else {
pet.bark(); // TypeScript knows 'pet' is definitely Dog
}
}How It Works & Key Takeaways
Type guards link runtime boolean checks directly to compile-time type resolution, eliminating dangerous `any` or explicit casting.
Mock Test · 1 Questions · Optional
Ready for Enums & Literal Types?
Take a quick test to evaluate yourself, or move straight to the next module.
Beginner1 questions