Combining Multiple Narrowing Techniques
What you'll learn: How to chain typeof, in, and custom type guards together to safely narrow complex nested union types.
Real-world types rarely submit to a single narrowing technique. When you're dealing with unions that mix primitives, objects with different shapes, and arrays, you'll need to stack multiple guards in sequence to safely access the values you need.
Why Combine Narrowing Techniques?
Think of narrowing like opening a series of locked doors. Each guard unlocks one door, revealing what's behind it and possibly more doors. A typeof check might confirm you have an object, then an in check narrows which kind of object, and finally a type predicate verifies a specific shape.
Chaining Guards Step-by-Step
type User = { kind: 'user'; name: string; age: number };
type Admin = { kind: 'admin'; name: string; permissions: string[] };
type Data = User | Admin | string | null;
function processData(data: Data): string {
// First: eliminate null with truthiness
if (!data) {
return "No data";
}
// Second: typeof to separate primitives from objects
if (typeof data === 'string') {
return data.toUpperCase();
}
// Third: in operator to check object shape
if ('permissions' in data) {
return `Admin: ${data.name}`;
}
// Fourth: what remains must be User
return `User: ${data.name}, age ${data.age}`;
}
Each guard narrows the union further, eliminating possibilities until TypeScript knows exactly what type remains. The order matters: check for null before using typeof, check typeof before using in, and the most specific checks should come last.
You can also combine discriminant properties with other guards, or use custom type predicates between typeof and in checks for maximum type safety in complex scenarios.
Key Takeaway: Chain narrowing techniques from broadest (truthiness, typeof) to most specific (in, predicates) to safely navigate complex nested union types through progressive elimination.