Sub topic 7
Pitfall: the constraint is not T
This chapter assumes you can write a generic function, you know extends constraints (T extends { id: number }), and you are comfortable with object types, unions, and literal types. It covers one error that surprises many people who are new to constraints, and the variants of it you will meet in real code.
The error
Start with a function that seems reasonable. It accepts anything with a numeric id and returns something with an id of 0.
function withId<T extends { id: number }>(item: T): T {
return { id: 0 };
// Error: Type '{ id: number; }' is not assignable to type 'T'.
// '{ id: number; }' is assignable to the constraint of type 'T',
// but 'T' could be instantiated with a different subtype of
// constraint '{ id: number; }'.
}The object { id: 0 } does satisfy the constraint { id: number }. The compiler still rejects it, because the return type is T, not { id: number }.
The constraint is a lower bound on what T has, not a value of T
A constraint says what every possible T must at least look like. It does not say what T is. Inside the function body, T stands for one specific type that the caller chose, and the body cannot know which one.
Take the call withId(employee), where employee has the type Employee.
interface Employee {
id: number;
name: string;
}For that call, TypeScript infers T = Employee, and the return type becomes Employee. A returned { id: 0 } has no name, so it is not an Employee. The caller was promised a value of its own type and got a smaller one.
The compiler checks the function once, for every possible T. A return value is accepted only if it is valid for all of them. { id: 0 } works for T = { id: number } and fails for T = Employee, so it is rejected.
What happens if you silence it
A type assertion removes the error and keeps the bug.
interface Employee {
id: number;
name: string;
}
function withIdUnsafe<T extends { id: number }>(item: T): T {
return { id: 0 } as T;
}
const emp: Employee = { id: 7, name: "Ada" };
const result = withIdUnsafe(emp); // typed as Employee
console.log(result.name.toUpperCase()); // TypeError at runtime: name is undefinedThe type system now claims that result.name is a string. At runtime it is undefined. This is why the error exists, and why as T is rarely the right fix.
Fixes that keep the types honest
The right fix depends on what the function is supposed to do.
Return a value derived from the input
If the result is the input with some changes, build it from the input. Spreading a value of type T produces the type T & { id: number }, which is assignable to T.
function withId<T extends { id: number }>(item: T): T {
return { ...item, id: 0 };
}
const reset = withId({ id: 7, name: "Ada" });
console.log(reset.name); // "Ada": the extra property survives, and the type says soThe extra properties are kept at runtime and in the type. That is what returning T means.
Return the constraint type instead
If the function creates a new value and has nothing to do with the caller's type, T is the wrong tool. Describe what you actually return.
function blankRecord(): { id: number } {
return { id: 0 };
}Ask whether T appears in the return type for a reason. If the output type does not depend on the input type, the function probably should not be generic.
Let the caller supply the value
When the function must produce a T but cannot build one, pass in something that can.
function make<T extends { id: number }>(build: () => T): T {
return build();
}
const e = make(() => ({ id: 1, name: "Grace" })); // { id: number; name: string }
console.log(e.name);The caller knows which T it wants, so the caller creates it. Factory parameters and the constructor pattern from the previous chapter work this way.
The same pitfall in other forms
The error is not limited to object literals. It appears whenever the body produces a value from the constraint's world and returns it as T.
Default values for parameters
A default value is also a fresh value, so it hits the same rule.
function configure<T extends { retries?: number }>(opts: T = {}): T {
// Error: Type '{}' is not assignable to type 'T'.
return opts;
}If T is { retries?: number; verbose: boolean }, then {} is not a valid T. Two safe options exist. If the function does not need to return the caller's exact type, annotate the parameter with the constraint.
interface Options {
retries?: number;
}
function configure(opts: Options = {}): Required<Options> {
return { retries: 3, ...opts };
}If the function does need to return the caller's type, require the argument or merge the defaults into the input.
function withDefaults<T extends { retries?: number }>(opts: T): T {
return { retries: 3, ...opts };
}
console.log(withDefaults({ verbose: true })); // { retries: 3, verbose: true }Narrowing does not refine the return type
Narrowing a constrained T with typeof lets you use the value, but a result computed from it is not a T.
function double<T extends string | number>(x: T): T {
if (typeof x === "string") {
return x + x; // Error: string is not assignable to T
}
return x * 2; // Error: number is not assignable to T
}If you call double("a"), T is the literal type "a". The result "aa" is a different string, so it cannot be of type "a". Overloads describe the relationship accurately.
function double(x: string): string;
function double(x: number): number;
function double(x: string | number): string | number {
return typeof x === "string" ? x + x : x * 2;
}
console.log(double("ab")); // "abab"
console.log(double(4)); // 8The cost is that a caller holding a string | number value cannot call double with it, because neither overload accepts the union. Add a third overload if you need that.
Literal types make the problem visible
Constraints on primitives show most clearly why the rule exists.
function pick<T extends string>(x: T): T {
return "default"; // Error: '"default"' is not assignable to type 'T'
}
const r = pick("a"); // T is "a", so r would be typed "a" but hold "default"The same reasoning rejects [] for T extends unknown[], because T might be a tuple such as [number, number]. It also rejects 0 for T extends number, because T might be the literal type 5.
Quick reference
| You write | Why it is rejected | Typical fix |
|---|---|---|
| `return { id: 0 }` in a function returning `T` | `T` may be a subtype with more properties | Return `{ ...item, id: 0 }` |
| `opts: T = {}` | The default is not necessarily a `T` | Annotate with the constraint, or require the argument |
| `return x + x` after `typeof x === "string"` | The result is a `string`, not the caller's `T` | Overloads, or return type `string` |
| `return "default"` for `T extends string` | `T` may be a single literal type | Take a `() => T` factory, or change the return type |
| `return []` for `T extends unknown[]` | `T` may be a tuple | Change the return type, or accept a factory |
What is still allowed
The constraint does give you everything it promises. Reading members works, and so does passing the value to code that accepts the constraint.
function describe<T extends { id: number; name?: string }>(item: T): string {
const label = item.name ?? "unnamed"; // reading constrained members is fine
return `${label} (#${item.id})`;
}
function takesConstraint(x: { id: number }): void {
console.log(x.id);
}
function forward<T extends { id: number }>(item: T): T {
takesConstraint(item); // T is assignable to its constraint
return item; // returning the input as T is always fine
}The direction matters. A T is assignable to its constraint. The constraint is not assignable to T. Most confusing errors in this area come from writing code that needs the second direction.
Choosing a fix
- If the result is the input with some changes, return a spread of the input.
- If the result has nothing to do with the caller's type, drop
Tfrom the return type and return the constraint type or a concrete type. - If the function must produce a
Tfrom nothing, accept a factory that creates one. - If different input types produce different output types, use overloads.
- Use
as Tlast, with a comment explaining why it is safe.
Exercise
This function should return a copy of a user with active set to true, and callers expect to get back their own user type. It does not compile. Explain why, and fix it without using as.
function activate<T extends { active: boolean }>(user: T): T {
return { active: true };
}
Show answer
The return value { active: true } satisfies the constraint but is not a T. If a caller passes { active: false, name: "Ada" }, T includes name, and the returned object would be missing it. TypeScript reports that T could be instantiated with a different subtype of the constraint. Build the result from the input instead: return { ...user, active: true };. The spread has the type T & { active: boolean }, which is assignable to T, and it keeps every other property of the caller's type.
Exercise
Given function first<T extends unknown[]>(items: T): T { return []; }, what type does first([1, 2] as [number, number]) claim to return, and why does the compiler reject the function body?
Show answer
It claims to return [number, number], a tuple with exactly two elements. The body returns [], an empty array, which is not a [number, number]. The compiler rejects the body because T could be a tuple type, and [] is only guaranteed to match the constraint unknown[], not every T. Fixes: return items or a value derived from it, or change the return type to unknown[] if an empty array is really what you want.