Sub topic 3
How TypeScript Infers Type Arguments
Most generic code you write never names its type arguments. You call firstElement([1, 2, 3]) and TypeScript works out T by itself. This chapter explains how it does that, so you can predict the result and fix the cases where the guess is wrong.
This chapter assumes you can write a basic generic function such as function identity<T>(value: T): T. It also assumes you know array types, union types, and arrow functions with type annotations.
What inference does
Inference is the compiler's process of choosing a type argument for each type parameter at a call site. It looks at the arguments you passed, and sometimes at the type the result is expected to have. It collects candidate types for each parameter and picks one.
function firstElement<T>(items: T[]): T | undefined {
return items[0];
}
const n = firstElement([1, 2, 3]); // number | undefined
const s = firstElement(["a", "b"]); // string | undefinedFor the first call, the compiler matches the parameter type T[] against the argument type number[]. Matching the two shapes gives one candidate for T, which is number. It then substitutes number for T everywhere in the signature, so the return type becomes number | undefined.
Inference follows structure
The compiler can infer through nested types, not only through a bare T. It lines up the parameter type with the argument type and records a candidate wherever T appears.
function valuesOf<T>(box: { value: T }): T[] {
return [box.value];
}
function keysOf<K, V>(map: Map<K, V>): K[] {
return Array.from(map.keys());
}
const v = valuesOf({ value: "x" }); // string[]
const k = keysOf(new Map([["a", 1]])); // string[]In keysOf, the argument has type Map<string, number>. The compiler matches it against Map<K, V> and gets K = string and V = number. The same matching works for arrays, tuples, Promise<T>, function types, and your own interfaces.
Inference through callbacks
Callbacks need an order of work, because a callback parameter's type may depend on a type parameter that is not inferred yet.
function map<T, U>(items: T[], fn: (item: T) => U): U[] {
const out: U[] = [];
for (const item of items) {
out.push(fn(item));
}
return out;
}
const lengths = map(["a", "bb"], (s) => s.length); // number[]The compiler treats (s) => s.length as context-sensitive, because s has no annotation. It sets that argument aside and infers T = string from items first. Then it uses T to give s the type string and checks the body. The body returns number, which becomes the candidate for U.
Because of this deferral, the order of parameters does not matter much. A callback can use a type inferred from a later argument. A callback with fully annotated parameters is not context-sensitive, so it contributes candidates in the first pass.
Several candidates for one parameter
When a type parameter appears in more than one place, each place adds a candidate. The compiler must then settle on one type.
function same<T>(a: T, b: T): T {
return a;
}
// same(1, "one");
// Error: Argument of type 'string' is not assignable to parameter of type 'number'.
same<string | number>(1, "one"); // OK: you chose the union yourselfFor unrelated primitives, the compiler does not build a union on its own. It takes the first candidate (number) and reports the second argument as a mismatch. You have two fixes:
- Supply the union explicitly, as shown above.
- Use two type parameters,
<A, B>, if the arguments do not need to match.
For object types, the compiler looks for one candidate that the others are assignable to. If one exists, it wins. If none does, you get an error like the one above.
Literal types: widened or kept
A literal such as "hi" has the literal type "hi" and also the wider type string. Which one becomes the type argument depends on the constraint.
function tag<T extends string>(value: T): T {
return value;
}
const t = tag("hi"); // "hi"
const items = firstElement(["a", "b"]); // string | undefined, not ("a" | "b")When T has a constraint that includes a primitive such as string, the compiler keeps the literal type. In firstElement, T has no such constraint, so array literal elements are widened to string. Add extends string when you want literal types preserved. Remove it when you want the wider type.
The expected result type
Sometimes there is nothing to infer from in the arguments. The compiler can then use the type the surrounding code expects for the result.
function empty<T>(): T[] {
return [];
}
const a = empty(); // unknown[]
const b: string[] = empty(); // T inferred as string from the annotationFor a, no candidate exists and nothing constrains T, so it becomes unknown. For b, the annotation provides the expected type string[]. The compiler matches T[] against it and gets T = string. Expect this behavior with new Set(), new Map(), Promise.resolve, and [] assigned to an annotated variable.
When there are no candidates
If nothing provides a candidate, the compiler uses the first of these that applies:
- The default type, if the parameter has one. Defaults get their own chapter.
- The constraint, if the parameter has one.
unknown.
A silent unknown is a common sign that you wrote a type parameter in a position where nothing can feed it.
Explicit type arguments are all or nothing
You can override inference by writing the type arguments yourself. You cannot give some and let the compiler infer the rest.
function convert<T, U>(input: T, fallback: U): T | U {
return input ?? fallback;
}
// convert<string>("a", 1);
// Error: Expected 2 type arguments, but got 1.
convert<string, number>("a", 1); // OK
convert("a", 1); // OK: both inferredIf you need to fix one type and infer another, split the work across two calls. A function that takes the first type argument and returns a function that infers the second is the usual pattern.
Blocking inference with NoInfer
Sometimes an argument should be checked against T without contributing a candidate. NoInfer<T>, added in TypeScript 5.4, marks a position that is excluded from inference.
function pickDefault<T extends string>(options: T[], fallback: NoInfer<T>): T {
return options.includes(fallback) ? fallback : options[0];
}
pickDefault(["red", "green"], "red"); // OK: T is "red" | "green"
// pickDefault(["red", "green"], "blue");
// Error: "blue" is not assignable to "red" | "green"Without NoInfer, the string "blue" would be a second candidate. The compiler would widen T to "red" | "green" | "blue" and accept the call, which defeats the check. This feature needs TypeScript 5.4 or later.
Common surprises
| What you see | Likely cause | Fix |
|---|---|---|
| `unknown` appears in a result | No candidates and no constraint | Add an argument that uses `T`, pass a type argument, or annotate the result |
| Error on the second argument | Two unrelated candidates for one `T` | Use two type parameters or pass the union explicitly |
| Literal type is lost | `T` has no primitive constraint | Add `extends string` (or `number`) |
| Literal type is too narrow | `T` has a primitive constraint | Remove the constraint or widen the argument |
| "Expected 2 type arguments" | Partial explicit arguments | Supply all of them, or supply none |
| Result is `any` | An argument of type `any` produced the candidate | Type the argument, or use `unknown` |
A debugging routine
When inference gives an unexpected type, work through these steps:
- Hover over the call and read the inferred type arguments.
- Find every place
Tappears in the parameter list. Each is a candidate source. - Check whether a constraint changes literal widening.
- Check for
anyin the arguments. - If the result is
unknown, check whether any argument can supply a candidate. - If the arguments conflict, decide whether they should share one type parameter.
Exercise
Given function merge<T>(a: T, b: T): T[] { return [a, b]; }, why does merge(1, "x") fail to compile, and how would you change the signature so the call compiles and returns (number | string)[]?
Show answer
Each argument adds a candidate for T: number from 1 and string from "x". The compiler does not combine unrelated primitives into a union, so it picks number and reports that "x" is not assignable to it. Two ways to fix it: call merge<number | string>(1, "x"), or give the function two type parameters, function merge<A, B>(a: A, b: B): (A | B)[], so each argument is inferred on its own.
Exercise
What is the type of x in const x = empty(); when function empty<T>(): T[] { return []; }, and what change makes x a number[] without writing a type argument?
Show answer
x is unknown[], because no argument or expected type provides a candidate for T. Annotating the variable, as in const x: number[] = empty();, gives the compiler an expected type to match T[] against, so T is inferred as number.