Sub topic 3
Constraining to Object Shapes, Interfaces, and Unions
Prerequisites and working model
Assume you know basic TypeScript types, interfaces, unions, and generic functions such as identity<T>(value: T): T. Familiarity with keyof is helpful, but this chapter focuses on object-shape constraints.
A generic type parameter is unconstrained until you restrict it. For example, TypeScript cannot allow value.id in this function:
function getId<T>(value: T) {
// return value.id; // Error: T might be a number, string, or other type
return value;
}The type parameter T could represent any type. An extends constraint narrows the types that T may represent:
function getId<T extends { id: number }>(value: T): number {
return value.id;
}The constraint says that every possible T must have an id property containing a number. The function body can safely read that property.
Constraining to an object shape
An object shape describes the properties that a value must have. You can write the shape inline:
function displayName<T extends { name: string }>(value: T): string {
return value.name;
}
const user = { name: "Ada", role: "admin" };
const product = { name: "Notebook", price: 12 };
console.log(displayName(user)); // Ada
console.log(displayName(product)); // NotebookBoth arguments satisfy the constraint. The user and product values have the required name property, even though they have different additional properties.
This behavior comes from structural typing. TypeScript checks whether a value has the required structure. It does not require the value to come from a particular class or declaration.
A constraint describes the minimum structure available inside the function. It does not erase the more specific type. If a function returns T, the caller can retain the original type:
function keepNamed<T extends { name: string }>(value: T): T {
return value;
}
const account = keepNamed({ name: "Ada", active: true });
account.active; // booleanThe constraint guarantees name, while T preserves active.
Using interfaces as constraints
An interface makes a constraint easier to reuse and document:
interface Identified {
id: number;
}
function idOf<T extends Identified>(value: T): number {
return value.id;
}
interface User extends Identified {
name: string;
}
interface Order extends Identified {
total: number;
}
const user: User = { id: 1, name: "Ada" };
const order: Order = { id: 42, total: 99.5 };
console.log(idOf(user)); // 1
console.log(idOf(order)); // 42User and Order both satisfy Identified, so the same function accepts either type. The generic parameter also preserves the specific argument type if the function returns T.
An interface constraint is still structural. This object does not explicitly implement Identified, but it is accepted because it has a compatible id property:
const shipment = { id: 7, carrier: "Parcel Express" };
idOf(shipment); // OKConstraining to a union
A constraint can be a union of object types. This is useful when a generic function accepts several known variants.
interface User {
kind: "user";
id: number;
name: string;
}
interface Order {
kind: "order";
id: number;
total: number;
}
function describe<T extends User | Order>(value: T): string {
if (value.kind === "user") {
return `User ${value.name} (#${value.id})`;
}
return `Order #${value.id}: $${value.total}`;
}
console.log(describe({ kind: "user", id: 1, name: "Ada" }));
console.log(describe({ kind: "order", id: 42, total: 99.5 }));The kind property is a discriminant. Its literal value tells TypeScript which union member is present. After checking value.kind, TypeScript allows access to name or total.
Without narrowing, code can use only members common to every union member. Both User and Order have id, but only User has name.
Common errors
A constraint is not an exact object type. T extends { id: number } accepts objects with extra properties. This is usually useful because it lets one function work with many related types.
A union constraint does not make every property available. For T extends User | Order, access to name requires a narrowing check first.
Optional properties also need handling. A constraint such as { nickname?: string } guarantees that the property may exist, but its value is still string | undefined. Code must check for undefined before treating it as a string.
Exercise
Write a generic function named hasId that accepts any value with a string id property and returns true when the id is not empty. What should its constraint be?
Show answer
Use function hasId<T extends { id: string }>(value: T): boolean { return value.id.length > 0; }. The constraint makes id available as a string inside the function.