Sub topic 3
Constraining to Object Shapes, Interfaces, and Unions
This chapter assumes you can write and call a simple generic function such as identity<T>(x: T): T. You should also know interfaces, type aliases, and union types. You have seen that T extends Something limits what a caller may pass. Here you will see which kinds of Something are most useful, and how each one changes what the function body can do.
Three kinds of constraint
A constraint is the type after extends. Most constraints you write fall into three groups:
- An object shape, written inline or as an interface, such as
{ id: number }. - A union of primitives or literals, such as
string | number. - A union or intersection of object types, such as
Circle | SquareorNamed & Timestamped.
In all three cases the rule is the same. The caller's type argument must be assignable to the constraint. Inside the body, TypeScript treats T as having the members of the constraint and nothing more.
Object shape constraints
The most common case is requiring that a value has certain properties. An interface keeps the requirement readable and reusable.
interface HasId {
id: number;
}
function indexById<T extends HasId>(items: T[]): Map<number, T> {
const map = new Map<number, T>();
for (const item of items) {
map.set(item.id, item);
}
return map;
}
const users = [
{ id: 1, name: "Ada" },
{ id: 2, name: "Linus" },
];
const byId = indexById(users);
console.log(byId.get(2)?.name); // LinusThe body can read item.id because T extends HasId guarantees it. The caller still gets Map<number, { id: number; name: string }>, so .name is available on the result.
Why not just write `HasId[]`?
You could declare the parameter as items: HasId[] and drop the generic. The call would compile, but the return type could only mention HasId.
interface HasId {
id: number;
}
function indexByIdLoose(items: HasId[]): Map<number, HasId> {
return new Map(items.map((item) => [item.id, item]));
}
const users = [{ id: 1, name: "Ada" }];
const loose = indexByIdLoose(users);
// loose.get(1)?.name; // Error: Property 'name' does not exist on type 'HasId'
console.log(loose.get(1)?.id); // 1The rule of thumb: if the output type should reflect more than the constraint, use a constrained type parameter. If the function only reads the constraint's members and returns nothing related to T, a plain parameter type is simpler.
Extra properties are allowed
A constraint describes a minimum, not an exact shape. TypeScript's structural typing accepts any type that has at least the required members. Passing an object literal with extra properties to a constrained generic does not trigger an excess property error, because T is inferred to include those properties.
interface HasId {
id: number;
}
function touch<T extends HasId>(item: T): T {
console.log(`touching ${item.id}`);
return item;
}
const result = touch({ id: 7, label: "seven" });
console.log(result.label); // sevenThis is the behavior you want in most APIs. If you need to forbid extra properties, a constraint is the wrong tool.
Combining shapes with intersections
When a value must satisfy several interfaces, join them with &.
interface Named {
name: string;
}
interface Timestamped {
createdAt: Date;
}
function describeRecord<T extends Named & Timestamped>(record: T): string {
return `${record.name} @ ${record.createdAt.toISOString()}`;
}
const text = describeRecord({
name: "report",
createdAt: new Date("2026-01-01T00:00:00Z"),
pages: 12,
});
console.log(text); // report @ 2026-01-01T00:00:00.000ZIntersections let you build small interfaces and combine them per function, instead of defining one large interface for every combination.
Choosing between `object`, `{}`, and `Record`
Sometimes you want to say "any object" without naming properties. Several constraints look similar but accept different things.
| Constraint | Accepts | Rejects |
|---|---|---|
| `object` | Objects, arrays, functions | Primitives such as `string`, `number` |
| `{}` | Everything except `null` and `undefined`, including primitives | `null`, `undefined` |
| `Record<string, unknown>` | Object literals and type aliases of object types | Interfaces without an index signature, arrays of class types in some cases |
| `Record<string, any>` | Interfaces, aliases, and class instances | Primitives |
The Record<string, unknown> row surprises many people. An interface does not get an implicit index signature, so it is not assignable to Record<string, unknown>. A type alias of the same shape is.
interface Config {
port: number;
}
type Settings = {
port: number;
};
function keysOf<T extends Record<string, unknown>>(obj: T): (keyof T)[] {
return Object.keys(obj) as (keyof T)[];
}
const settings: Settings = { port: 8080 };
console.log(keysOf(settings)); // [ 'port' ]
declare const config: Config;
// keysOf(config); // Error: Index signature for type 'string' is missing in type 'Config'If the function accepts any object and does not care about its keys, T extends object avoids the problem. If you need indexed access and must accept interfaces, Record<string, any> works, at the cost of any leaking into the body.
Union constraints
A union constraint limits T to a fixed set of types. For primitives, the typical use is accepting several types while keeping the exact type for the caller.
function echo<T extends string | number>(value: T): T {
return value;
}
const a = echo("hi"); // type: "hi"
const b = echo(42); // type: 42
// echo(true); // Error: boolean is not assignable to string | number
function padded<T extends string | number>(value: T, width: number): string {
return String(value).padStart(width, "0");
}
console.log(padded(7, 3)); // 007
console.log(padded("ab", 4)); // 00abNotice the literal types "hi" and 42 in the results. When the constraint includes primitive types, TypeScript keeps literal types during inference instead of widening them to string and number. This is a handy way to capture literal values without writing as const.
What the body can do with a union constraint
Inside the body, T is only known to be assignable to the union. You can use operations that are valid for every member of the union, such as String(value) above. You cannot call a method that exists on only one member.
function broken<T extends string | number>(value: T): number {
// return value.length; // Error: Property 'length' does not exist on type 'string | number'
return String(value).length;
}This is the same limitation as with an ordinary union parameter. A constraint does not give the body extra knowledge. It only restricts the callers.
Unions of object types
The same rules apply to unions of object types. Only the members common to every branch are available.
interface Circle {
kind: "circle";
radius: number;
}
interface Square {
kind: "square";
size: number;
}
function kindOf<T extends Circle | Square>(shape: T): T["kind"] {
return shape.kind; // common to both members
// shape.radius would be an error: Square has no 'radius'
}
const k = kindOf({ kind: "circle", radius: 2 });
console.log(k); // circleThe return type T["kind"] is more precise than "circle" | "square". For the call above, it is "circle".
A common error: reading the constraint as T
A constraint tells you what T is at least. It does not tell you that T equals the constraint. A function that tries to construct a value of the constraint and return it as T will fail, and the next chapters return to this in detail. For now, remember that inside the body you may read the constrained members of a T value, but you may not manufacture one.
Choosing a constraint: summary
| You want to... | Write | Why | Column |
|---|---|---|---|
| Read specific properties of an argument | `T extends { id: number }` or an interface | Minimum shape, extra properties allowed | |
| Require several capabilities | `T extends A & B` | The type argument must satisfy both | |
| Accept a fixed set of primitives and keep literals | `T extends string \ | number` | Inference preserves literal types |
| Accept any non-primitive | `T extends object` | Excludes primitives, no property access | |
| Accept any object with string keys | `T extends Record<string, any>` | Interfaces are accepted, but `any` leaks |
Exercise
The function below fails to compile at the commented line. Rewrite its signature so it compiles and so that last([{ id: 1, tag: "a" }]) returns a value whose type still has the tag property.
function last(items: { id: number }[]) {
return items[items.length - 1];
}
// const x = last([{ id: 1, tag: "a" }]);
// x.tag; // Error: Property 'tag' does not exist on type '{ id: number; }'
Show answer
Make the element type a constrained type parameter: function last<T extends { id: number }>(items: T[]): T { return items[items.length - 1]; }. T is inferred as { id: number; tag: string }, so x.tag is allowed. The constraint still guarantees that each item has an id. With a plain { id: number }[] parameter the return type could only mention id.
Exercise
Why does keysOf(config) fail when config has the interface type Config { port: number }, but succeed when the value has the alias type Settings = { port: number }, given T extends Record<string, unknown>? Name two ways to change the constraint so that both calls compile.
Show answer
Type aliases of object literal types get an implicit index signature, so they are assignable to Record<string, unknown>. Interfaces do not, so Config is rejected with "Index signature for type 'string' is missing". Either use T extends object (no index access needed) or T extends Record<string, any>, which accepts interfaces. Declaring an explicit index signature on the interface also works but changes its meaning.
Exercise
Given function echo<T extends string | number>(value: T): T, what is the type of echo("hi"), and why is it not string?
Show answer
It is "hi". Because the constraint includes primitive types, TypeScript keeps the literal type when inferring T instead of widening it to string.