Sub topic 7
Pitfall: the constraint is not `T`
Assume you know basic TypeScript types, interfaces, unions, and generic functions. You should also be familiar with the syntax T extends SomeType, which restricts the types that can be used for T.
A generic constraint tells TypeScript what is definitely known about a type parameter. It does not replace that type parameter. The actual type chosen for T can be more specific than the constraint.
A constrained type parameter can be a narrower type
Consider this function:
function withId<T extends { id: number }>(item: T): T {
return item;
}The constraint says that every valid T must have an id property whose value is a number. However, callers can choose a type with additional properties:
const book = withId({
id: 1,
title: "TypeScript Guide"
});
// T is:
// {
// id: number;
// title: string;
// }Inside withId, TypeScript knows that item.id exists. It also knows that item has the complete type T, including any properties chosen by the caller.
The constraint { id: number } describes the minimum shape that T must have. It does not describe the complete shape of T.
Why returning a fresh constraint-shaped value fails
This version looks as though it should work:
function withId<T extends { id: number }>(item: T): T {
return { id: 0 };
}It fails because the returned object has the constraint's shape, not necessarily the caller's exact T.
For example, TypeScript could instantiate the function with this type:
interface User {
id: number;
name: string;
}
const user: User = { id: 1, name: "Ada" };If withId(user) were allowed to return { id: 0 }, the result would be missing the required name property. The returned value satisfies { id: number }, but it does not satisfy User.
The safe implementation returns the original item, because it already has type T:
function resetId<T extends { id: number }>(item: T): T {
return { ...item, id: 0 };
}
interface User {
id: number;
name: string;
}
const user: User = { id: 1, name: "Ada" };
const reset = resetId(user);
console.log(reset.name); // AdaThe spread operation copies all properties from item. The new id value still has type number, so the result preserves the caller's other properties.
A constraint controls access, not construction
Inside a generic function, the compiler allows operations supported by the constraint:
function logId<T extends { id: number }>(item: T): void {
console.log(item.id);
}The function cannot safely construct an arbitrary T from only an id, because T might contain required fields that are unknown to the function.
This distinction appears in many generic APIs:
- A constraint lets a function read shared properties.
- A constraint limits which arguments are accepted.
- A constraint does not reveal every property of the actual type.
- A constraint does not let a function create a complete value of
T.
If a function needs to create a value, change the API so the caller supplies the missing information, or return the constraint type instead of T.
function makeIdRecord(): { id: number } {
return { id: 0 };
}
function replaceId<T extends { id: number }>(
item: T,
id: number
): T {
return { ...item, id };
}makeIdRecord promises only the constraint shape. replaceId promises the original specific type and therefore preserves the original properties.
Check the return type carefully
When reviewing a generic function, ask what its return type promises. These functions make different promises:
function asRecord<T extends { id: number }>(
item: T
): { id: number } {
return { id: item.id };
}
function preserveItem<T extends { id: number }>(
item: T
): T {
return item;
}The first function may discard extra properties because it returns only { id: number }. The second function must preserve the complete type T.
Exercise
Why is return { id: 0 } invalid in a function returning T where T extends { id: number }, and what is one safe alternative?
Show answer
T may be a narrower type with additional required properties, so an object containing only id may be incomplete. Return the original item, return a value built by copying item, or change the return type to the constraint.