How does TypeScript narrow a discriminated union when the discriminant check happens inside a called function rather than inline?
Short answer
By default, TypeScript does NOT narrow based on an external function's return value unless that function is declared as a user-defined type predicate (using the 'x is Type' return type syntax) — a plain boolean-returning helper won't narrow the union at the call site, even if…
Advertisement
AModel answer
By default, TypeScript does NOT narrow based on an external function's return value unless that function is declared as a user-defined type predicate (using the 'x is Type' return type syntax) — a plain boolean-returning helper won't narrow the union at the call site, even if its logic is equivalent to an inline check.
function isCircle(shape: Shape): shape is Circle {
return shape.kind === 'circle'; // type predicate enables narrowing
}
function badIsCircle(shape: Shape): boolean {
return shape.kind === 'circle'; // plain boolean does NOT narrow
}
if (isCircle(shape)) { shape.radius; } // works
// if (badIsCircle(shape)) { shape.radius; } // Error: radius doesn't exist on ShapeReal-world example
Extracting a reusable, well-typed 'isX' check into a shared utility function used across multiple switch/if statements.
Likely follow-ups
- What is the exact syntax for declaring a custom type predicate function?
Related topics