How would you implement a type-level 'if-else chain' to classify a type into one of several categories?
Short answer
Chain multiple conditional types together, where the false branch of one conditional type is itself another conditional type — mirroring a JavaScript if/else-if/else chain, evaluated entirely at the type level.
Advertisement
AModel answer
Chain multiple conditional types together, where the false branch of one conditional type is itself another conditional type — mirroring a JavaScript if/else-if/else chain, evaluated entirely at the type level.
type TypeName<T> =
T extends string ? 'string' :
T extends number ? 'number' :
T extends boolean ? 'boolean' :
T extends undefined ? 'undefined' :
T extends Function ? 'function' :
'object';
type A = TypeName<42>; // 'number'Real-world example
Building a type-level classifier used internally by advanced utility types or a runtime type-checking helper's return type.
Likely follow-ups
- Is there a practical limit to how many conditions you can chain before the compiler slows down significantly?
Related topics