Sub topic 2
Using One Type Parameter to Constrain Another
Assume you know basic generic functions, union types, keyof, and indexed access types. A constraint can make one type parameter depend on another.
Constraining Keys with `keyof`
K extends keyof T means that K must be one of the property names in T. The return type T[K] then matches the selected property.
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
const id = getProp(user, "id"); // number
// getProp(user, "email"); // Error: "email" is not a key of userThe relationship between T, K, and T[K] prevents invalid property access while preserving the precise result type.
Constraining Constructor Types
A constructor type describes a value that can be called with new. Use new (...args: any[]) => T when a function should receive a class and create an instance.
type Constructor<T = object> = new (...args: any[]) => T;
function createInstance<T>(ctor: Constructor<T>): T {
return new ctor();
}
class Point {
x = 0;
y = 0;
}
const point = createInstance(Point); // PointTypeScript infers T from the constructor, so the result retains the class type.
Pitfall: The Constraint Is Not `T`
A constraint describes the minimum guarantees about T. It does not mean that every value matching the constraint is a valid T.
function withId<T extends { id: number }>(item: T): T {
// return { id: 0 }; // Error
return item;
}T might contain additional required properties. Returning only { id: 0 } could discard them. Return the original value or a value whose type is known to be exactly T.
Giving a Type Parameter a Default
A default lets callers omit a type argument when the common choice is known.
interface ApiResponse<TData = unknown, TError = Error> {
data?: TData;
error?: TError;
}
const response: ApiResponse<string> = { data: "ok" };Required type parameters must come before parameters with defaults. A default must also satisfy its constraint.
Exercise
Why is getProp(user, "email") rejected?
Show answer
"email" is not assignable to keyof typeof user, so it cannot satisfy K extends keyof T.