Sub topic 1
TypeScript Generic Constraints: Why Unconstrained Type Parameters Are Limiting
Prerequisites
Assume you know basic TypeScript types, interfaces, unions, type aliases, and simple generic functions such as identity<T>(value: T): T. Familiarity with keyof and indexed access types is useful.
Why Unconstrained Type Parameters Are Limiting
A generic type parameter can represent many possible types. Without a constraint, TypeScript only knows that a value has the type T. It cannot assume that T has any particular property.
function describe<T>(value: T): string {
// return value.name; // Error: Property 'name' does not exist on type 'T'
return String(value);
}The function must work for every possible T, including number, boolean, or an object without a name property. The compiler therefore rejects property access that is not guaranteed for every possible type.
Restricting a Type Parameter with `extends`
An extends constraint limits the types that a type parameter can represent. This lets the function body use members guaranteed by the constraint.
function longest<T extends { length: number }>(a: T, b: T): T {
return a.length >= b.length ? a : b;
}
longest([1, 2, 3], [1, 2]); // T is number[]
longest("ab", "abc"); // T is string
// longest(10, 20); // Error: number has no 'length'Here, T may be an array, string, or another compatible type. It must have a numeric length property.
Constraining to Object Shapes, Interfaces, and Unions
You can express a required object shape with an inline type, an interface, or a union.
interface Identified {
id: number;
}
function getId<T extends Identified>(item: T): number {
return item.id;
}
type StringOrNumber = string | number;
function echo<T extends StringOrNumber>(value: T): T {
return value;
}A constraint describes the minimum features a type must provide. A type with extra properties still satisfies an object-shaped constraint.
> callout note > A constraint limits valid type arguments and describes what the function may safely use. It does not replace the specific type argument.
Constraining Keys with `keyof`
keyof T produces a union of the property names known for T. Constraining K with keyof T keeps a key and its object connected.
function getProp<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}
const user = { id: 1, name: "Ada" };
const name = getProp(user, "name"); // string
// getProp(user, "email"); // Error: not a key of userT[K] is the type of the selected property, so the return type changes with the key.
Exercise
Why does value.name fail in an unconstrained generic function?
Show answer
Because T might be instantiated with a type that has no name property.