Sub topic 13
Reading errors that involve generics
This chapter assumes you can read the basic diagnostic format (file, position, code, message) and understand assignability and message chains from the earlier chapters. You should also know the syntax of a generic function such as function f<T>(x: T): T.
Generic errors look harder than other errors because the message names type parameters like T instead of concrete types. The approach is the same as before: find the outermost claim, follow the chain to the root cause, and then work out what each type parameter was bound to.
What is different about generic errors
A generic function has two kinds of types: type parameters (T, K, V) and the concrete types the compiler substitutes for them at each call. An error can come from either side.
- At a call site, the compiler has already replaced
Twith a concrete type, so the message shows that type. Your job is to find out why it chose that type. - Inside the generic body,
Tis still unknown, so the message namesTitself. Your job is to see that the code assumes something aboutTthat the compiler cannot prove.
Check which side you are on before you change anything.
Call-site errors: what did T become?
When a type parameter appears in several parameters, the compiler infers it from the arguments, usually taking the first candidate it finds. Later arguments are then checked against that choice.
function pair<T>(a: T, b: T): [T, T] {
return [a, b];
}
pair(1, "two");The compiler reports TS2345 on "two": Argument of type 'string' is not assignable to parameter of type 'number'. The message never mentions T. It shows what T became (number, from the first argument) and then objects to the second argument. If the mixed types are intentional, state the type argument yourself:
function pair<T>(a: T, b: T): [T, T] {
return [a, b];
}
const mixed = pair<number | string>(1, "two");
console.log(mixed);If they are not intentional, fix the argument. Do not widen T just to make the message go away.
In an editor, hover over the function name at the call site. The tooltip shows the signature with the inferred types substituted, for example pair<number>(a: number, b: number). This is the quickest way to see what the compiler decided.
Constraint violations
A constraint such as T extends { length: number } limits which types may be substituted. When an argument fails the constraint, the message names the constraint, not T.
function longest<T extends { length: number }>(a: T, b: T): T {
return a.length >= b.length ? a : b;
}
longest(10, 20);The error is TS2345: Argument of type 'number' is not assignable to parameter of type '{ length: number; }'. Read it as "the parameter type is the constraint, and number does not satisfy it". Passing "abc" or [1, 2] works, because both have a numeric length.
Errors inside a generic body
Inside the function, T could be any type that meets its constraint. The compiler therefore rejects code that returns or assigns a concrete value where T is expected.
function makeDefault<T>(): T {
return {};
}This gives TS2322: Type '{}' is not assignable to type 'T'. The compiler adds a second line, 'T' could be instantiated with an arbitrary type which could be unrelated to '{}'. That line is the root cause. A caller could write makeDefault<string>(), and {} is not a string.
The fix is to get a T from somewhere that is guaranteed to supply one, such as a parameter:
function withDefault<T>(value: T | undefined, fallback: T): T {
return value ?? fallback;
}
console.log(withDefault<number>(undefined, 5));Errors on built-in generic types
Many errors you meet daily involve generic types from the standard library, such as Array<T>, Promise<T>, and Map<K, V>. The angle brackets tell you what the type holds. Read Promise<string> as "a promise of a string", which is not the same type as string.
async function load(): Promise<string> {
return "data";
}
async function main(): Promise<void> {
const text: string = load();
console.log(text);
}
main();The error is TS2322: Type 'Promise<string>' is not assignable to type 'string'. The fix is await load(). When you see a Promise<...> where you expected the inner type, you have almost certainly forgotten an await.
Method calls on generic containers report errors in terms of the element type. With const ids: Array<number> = [], the call ids.push("7") reports TS2345: Argument of type 'string' is not assignable to parameter of type 'number'. The parameter type number comes from Array<number>, not from anything in your call.
Mismatched type arguments
Two instances of the same generic type are assignable only if their type arguments are compatible. The chain shows where they differ.
const scores = new Map<string, number>();
const labels: Map<string, string> = scores;The outer line says Type 'Map<string, number>' is not assignable to type 'Map<string, string>'. The line beneath it narrows this to the differing argument: Type 'number' is not assignable to type 'string'. The key types match, so only the value type is at fault. Follow the chain to its last line to find which type argument disagrees.
Common phrases and what they mean
| Phrase in the message | What it usually means |
|---|---|
| `not assignable to type 'T'` | Code inside a generic body assumes a concrete type for `T` |
| `'T' could be instantiated with an arbitrary type` | The compiler is explaining why it cannot trust that assumption |
| `Argument of type ... is not assignable to parameter of type '{ ... }'` | An argument failed a `extends` constraint |
| `Promise<X>` where `X` was expected | A missing `await` |
| `Type 'A<X>' is not assignable to type 'A<Y>'` | The type arguments differ; read the next line |
| `Type instantiation is excessively deep` | A recursive or very large type; simplify it or add a base case |
A working routine
- Decide whether the error is at a call site or inside a generic body.
- At a call site, hover to see what each type parameter was inferred as, and compare that to what you intended.
- Inside a body, ask what the compiler is not allowed to assume about
T, and either add a constraint (T extends ...) or change the code so it receives aTinstead of inventing one. - If you must override inference, pass the type argument explicitly (
fn<Type>(...)) rather than asserting on the result.
Exercises
Exercise
The call longest(10, 20) on a function declared longest<T extends { length: number }>(a: T, b: T): T reports that number is not assignable to { length: number; }. Name two ways to fix the call without changing the function.
Show answer
Pass arguments that have a numeric length, such as strings (longest("ab", "abc")) or arrays (longest([1], [1, 2])). The other option is to convert the numbers to a type that has length, for example String(10). Changing the function to remove the constraint is not needed, and adding as any would hide a real misuse.
Exercise
Why does function make<T>(): T { return {}; } fail, and what change to the signature makes it compile honestly?
Show answer
Inside the body T is unknown, and a caller may choose any type for it, such as string, so {} is not guaranteed to be a T. Make the function receive a T from its caller, for example function make<T>(value: T): T { return value; }, or take a factory parameter () => T.