Advertisement
Advanced TypeScript, Conditional Types

How does a conditional type distinguish between 'any' and other types, given any is assignable to (and from) everything?

Short answer

Because 'any' is compatible with virtually any type check, a naive conditional type applied to 'any' tends to resolve to a union of BOTH branches (the true and false results) rather than picking one — since the compiler can't determine which branch is correct when the input…

Save TypeScript mock interview
Advertisement
AModel answer
Because 'any' is compatible with virtually any type check, a naive conditional type applied to 'any' tends to resolve to a union of BOTH branches (the true and false results) rather than picking one — since the compiler can't determine which branch is correct when the input could be anything.
type Test<T> = T extends string ? 'yes' : 'no';
type A = Test<any>; // 'yes' | 'no' -- both branches, not just one
Real-world example
Debugging a confusing conditional type result that unexpectedly includes both branches, tracing it back to an 'any' leaking into the type parameter.
Likely follow-ups
  • How would you write a conditional type that specifically detects whether a type IS 'any'?
Related topics