Skip to content

Generic type inference produces unexpected type

Quick summary

Your generic function's type parameter was inferred as a wider type than intended — the resulting type is too permissive.

Why this happens

  • TypeScript inferred the generic as the common supertype (e.g., string | number instead of string)

  • The generic constraint is too loose, allowing types you did not intend to support

  • Multiple type arguments were inferred from the same value, causing them to unify to a broader type

Minimal example

✗ Broken code
function pair<T>(a: T, b: T): T[] { return [a, b]; }
const result = pair('hello', 'world'); // inferred as string[], not ['hello', 'world']
✓ Fixed code
function pair<T>(a: T, b: T): T[] { return [a, b]; }
const result = pair('hello' as const, 'world' as const); // inferred as ('hello' | 'world')[]
// Or TS 5.0+: function pair<const T>(a: T, b: T): T[]

Using 'as const' on the arguments tells TypeScript to infer literal types, giving a narrower and more precise result type.

How to diagnose

  • Hover over the function call in your IDE to see the inferred type parameters

  • Add explicit type arguments to the call to see if the issue is with inference or the function itself

  • Check the generic constraints and default types to understand why TypeScript chose the broader type

How to fix

  • Provide explicit type arguments at the call site: func<string>(value) instead of relying on inference

  • Add a 'const' type parameter (TS 5.0+) or use 'as const' on the argument to get a narrower inferred type

  • Tighten the generic constraint with 'extends' to limit the types that can be inferred

How to prevent

  • Add explicit type arguments when the inferred type is critical for correctness

  • Use const type parameters or 'as const' for functions that should infer literal types

Related Resources

Related Glossary

Related Lessons

← Back to language