Advertisement
Advanced TypeScript, Generics

How does generic type inference work across multiple arguments, and what happens when they conflict?

Short answer

TypeScript tries to find the single type T that's compatible with ALL usages across the arguments — when arguments suggest different types for the same T, TypeScript computes their union (the most general type compatible with every usage) rather than raising an immediate error…

Save TypeScript mock interview
Advertisement
AModel answer
TypeScript tries to find the single type T that's compatible with ALL usages across the arguments — when arguments suggest different types for the same T, TypeScript computes their union (the most general type compatible with every usage) rather than raising an immediate error, unless that union is truly incompatible with a constraint.
function combine<T>(a: T, b: T): T[] {
  return [a, b];
}
combine(1, 2);         // T inferred as number
combine(1, 'two');     // T inferred as string | number, NOT an error
Real-world example
Understanding why passing mismatched-looking arguments to a generic function widens the inferred type into a union rather than immediately failing.
Likely follow-ups
  • How would you force T to be a single consistent type instead of allowing this union-widening behavior?
Related topics