Q12: What are User-Defined Type Guards using custom Type Predicates (`value is T`)?
A User-Defined Type Guard is a function whose return type signature uses a Type Predicate in the form parameterName is Type.
When the function returns true, TypeScript narrow the argument's type in the calling conditional block.
Custom Type Guard Function
interface Fish { swim: () => void }
interface Bird { fly: () => void }
// Custom Type Guard
function isFish(pet: Fish | Bird): pet is Fish {
return (pet as Fish).swim !== undefined;
}
function move(pet: Fish | Bird) {
if (isFish(pet)) {
pet.swim(); // Narrowed safely to Fish
} else {
pet.fly(); // Narrowed safely to Bird
}
}💡 The pet is Fish predicate instructs TypeScript to treat pet as Fish inside the true branch.
Key Takeaways
- Type predicates (
arg is T) allow custom type narrowing logic. - Used to encapsulate custom type-validation runtime logic.