How do you restrict a generic type parameter using extends?
Write T extends Something to say the caller may pass any type, as long as it has at least the shape of Something. Inside the function you can then safely use those members, such as .length or .id.
Explain it simply
A plain T is like a blank form: it accepts anything, so inside the function you cannot assume it has any fields. A constraint is a rule printed on the form: "must have a name and a roll number".
T extends { id: number } means: any type is welcome, provided it contains an id that is a number. Extra fields are fine. The function can read id, and TypeScript still remembers the full original type for the return value.
Example
function longest<T extends { length: number }>(a: T, b: T): T {
return a.length >= b.length ? a : b; // .length is safe
}
console.log(longest("Pune", "Delhi")); // "Delhi"
console.log(longest([1, 2, 3], [4, 5])); // [1, 2, 3]
// longest(10, 20); // Error: number has no 'length'
function findById<T extends { id: number }>(items: T[], id: number): T | undefined {
return items.find(item => item.id === id);
}
const found = findById([{ id: 1, name: "Asha" }], 1); // type keeps 'name'What to say in the interview
"extends in a type parameter sets a minimum shape. It lets me use known members inside the function while still returning the caller's exact type, rather than the narrow constraint type. Without it I would either cast or fall back to any."
Common mistakes
- Writing the function to return the constraint type ({ id: number }) and losing the extra fields.