Skip to content
jshacks.dev
TypeScript

Generic Constraints With extends

Limit what a type parameter can be with extends so your generic function can use its properties. Covers keyof constraints, errors and the subtype trap.

8 min read
Summarize in AI
Flat illustration of an editor window full of code, with the TypeScript, Node.js, npm and JavaScript logos.

A type parameter on its own is a blank. The compiler knows nothing about T except that it exists, so the body of a generic function can pass it around but cannot read a property from it or call a method on it. A constraint fills in what you know: T extends { id: string } says that whatever type the caller uses, it has to have a string id. Inside the function you can then rely on that, and outside it the caller gets back their own specific type and not just the constraint. This post shows the syntax, the most useful constraint patterns including keyof, the errors a violated constraint produces, and a subtle trap where a constrained return type rejects a perfectly reasonable value. It uses TypeScript 6.x, and the reference is the handbook section on generic constraints.

The basic form

A constraint is written after the type parameter with extends. The constraint can be any type: an object shape, an interface, a union, a function type, or another type parameter.

by-id.tsTypeScript
function byId<T extends { id: string }>(items: T[], id: string): T | undefined {
  return items.find((item) => item.id === id);
}

const users = [
  { id: "u1", name: "Ada", admin: true },
  { id: "u2", name: "Grace", admin: false },
];

const found = byId(users, "u2");
console.log(found?.name, found?.admin);
Text
Grace false

The body reads item.id because the constraint guarantees it. The result type is T | undefined, where T is the full shape of the user objects, including name and admin. If the function took { id: string }[] and returned { id: string } | undefined, the caller would lose name and admin and would need a cast to get them back. Keeping T is what the generic form buys you.

When the argument does not satisfy the constraint, the compiler says so at the call.

by-id-bad.tsTypeScript
function byId<T extends { id: string }>(items: T[], id: string): T | undefined {
  return items.find((item) => item.id === id);
}

const rows = [{ name: "Ada" }];
byId(rows, "1");
Text
by-id-bad.ts(6,6): error TS2345: Argument of type '{ name: string; }[]' is not assignable to parameter of type '{ id: string; }[]'.
  Property 'id' is missing in type '{ name: string; }' but required in type '{ id: string; }'.

The second line of the message names the property that breaks the constraint, which is where to look first.

Constraints from an interface

Naming the shape as an interface is clearer once more than one function uses it.

entity.tsTypeScript
interface Entity {
  id: string;
  updatedAt: number;
}

function latest<T extends Entity>(entities: T[]): T | undefined {
  let best: T | undefined;
  for (const entity of entities) {
    if (best === undefined || entity.updatedAt > best.updatedAt) {
      best = entity;
    }
  }
  return best;
}

const posts = [
  { id: "p1", updatedAt: 100, title: "Generics" },
  { id: "p2", updatedAt: 300, title: "Constraints" },
  { id: "p3", updatedAt: 200, title: "Defaults" },
];

console.log(latest(posts)?.title);
Text
Constraints

An object type satisfies the constraint through structure. The post objects never mention Entity, and they qualify because they have the required properties with the right types. That is the structural typing the language uses everywhere, and it keeps constraints cheap to adopt.

Constraining one parameter by another with keyof

The most useful constraint relates two type parameters. A function that reads a property by name should accept only names that exist on the object. The keyof operator produces the union of an object type's keys, and K extends keyof T limits K to them.

get-property.tsTypeScript
function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
  return obj[key];
}

const user = { name: "Ada", age: 36 };

console.log(getProperty(user, "name"));
console.log(getProperty(user, "age") + 1);
Text
Ada
37

The result type T[K] is an indexed access type: the type of property K on T. For "name" it is string, and for "age" it is number, which is why adding one to the second result type-checks. A typo is caught at the call.

get-property-typo.tsTypeScript
function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
  return obj[key];
}

const user = { name: "Ada", age: 36 };

getProperty(user, "nmae");
Text
get-property-typo.ts(6,19): error TS2345: Argument of type '"nmae"' is not assignable to parameter of type '"name" | "age"'.

The message lists the legal keys, so a misspelling is fixed from the error alone. Both keyof and indexed access types have their own posts in this series.

Constraining to functions and constructors

A constraint can describe something callable. This lets a generic function accept any function while remembering its exact signature, using the built-in utility types.

timed.tsTypeScript
function callTwice<F extends (value: number) => number>(fn: F, value: number): number {
  return fn(fn(value));
}

const double = (n: number) => n * 2;
console.log(callTwice(double, 5));

function build<T>(factory: new () => T): T {
  return new factory();
}

class Counter {
  count = 0;
}

console.log(build(Counter).count);
Text
20
0

The second function shows a constructor type, new () => T, which is how you write a generic factory. Passing the class itself, not an instance, satisfies it, and T is inferred as Counter.

Multiple constraints with intersections

A type parameter has one extends clause, and to require several things you combine them with &.

multiple.tsTypeScript
interface HasId {
  id: string;
}

interface HasName {
  name: string;
}

function label<T extends HasId & HasName>(item: T): string {
  return `${item.id}: ${item.name}`;
}

console.log(label({ id: "u1", name: "Ada", role: "admin" }));
Text
u1: Ada

The extra role property is allowed because the argument is not a fresh object literal assigned directly to a parameter of the exact constraint type. Excess property checks apply to a literal assigned to a known object type, and here T is inferred as the literal's own type, which satisfies the constraint with room to spare.

The subtype trap

A constraint tells the compiler the minimum. It does not tell it what T really is. That gap shows when a function with a constrained return type tries to build a result.

trap.tsTypeScript
function reset<T extends { id: string }>(item: T): T {
  return { id: "" };
}
Text
trap.ts(2,10): error TS2322: Type '{ id: string; }' is not assignable to type 'T'.
  '{ id: string; }' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint '{ id: string; }'.

The compiler is protecting the caller. If someone calls reset with an object that also has name, the promised return type is that full object, and { id: "" } has no name. The error is correct even though it feels pedantic. There are three honest fixes: return the constraint type if the caller does not need the original back, copy the input and change one field with a spread, or let the compiler know what you did with an assertion you can defend.

trap-fixed.tsTypeScript
function reset<T extends { id: string }>(item: T): T {
  return { ...item, id: "" };
}

const result = reset({ id: "u1", name: "Ada" });
console.log(result);
Text
{ id: '', name: 'Ada' }

Spreading keeps every other property, so the result really is a T with a replaced id.

What a constraint does not do

A constraint is checked at the call, and it does not change what the value is at runtime. It cannot make the compiler treat T as the constraint inside the body for assignments either: you can read item.id, and you cannot write a new object of type T from scratch, as the trap shows. Another surprise is that a constraint on a primitive such as T extends string keeps literal types. T extends string called with "north" infers "north", not string, which is useful for lookup keys and surprising when you wanted to widen.

literal.tsTypeScript
function echo<T extends string>(value: T): T {
  return value;
}

const direction = echo("north");
const text: "north" = direction;
console.log(text);
Text
north

The inferred type of direction is the literal "north", so the assignment compiles. The same effect makes constrained generics a good fit for event names and route keys.

Reading a constraint error

When a call fails because of a constraint, read the message from the bottom up. The last line names the missing or mismatched member, and the first line names the two types being compared. If the argument is a variable, check where the variable was declared, because a type widened earlier in the program is the usual cause. If the argument is an object literal built inline, compare each property against the constraint, since a typo such as Id for id produces exactly the missing-property message shown above.

Constraints also appear in library signatures you do not control. When a call into a library reports that your argument is not assignable to a constraint, the fix is almost always on your side: add the missing property, or narrow the type you pass. Resist the urge to cast the argument, because the library's body relies on the property being there and will fail at runtime instead.

Testing constrained functions

Test a constrained function with a value that has more than the constraint requires, and check that the extra data survives. That is the property the constraint exists to protect.

by-id.test.tsTypeScript
import { deepStrictEqual } from "node:assert/strict";
import { byId } from "./by-id.js";

const users = [{ id: "u1", name: "Ada" }];

deepStrictEqual(byId(users, "u1"), { id: "u1", name: "Ada" });
deepStrictEqual(byId(users, "missing"), undefined);

console.log("constraint cases passed");
Text
constraint cases passed

When not to constrain

If the function only needs the constraint type and never returns T, take the constraint type as a plain parameter. function describe(item: { id: string }) is simpler than function describe<T extends { id: string }>(item: T), and the two behave the same for the caller. Reach for extends when the output depends on the input type, or when one type parameter has to relate to another, as with keyof.

Share

Keep reading

Flat illustration of two options weighed side by side, with the TypeScript, Node.js, npm and JavaScript logos.
TypeScript

Type Annotations vs Type Assertions

A type annotation asks the compiler to check a value, while an assertion tells it to trust you. Learn the difference, the errors and safer alternatives.

6 min read
Flat illustration of an editor window full of code, with the TypeScript, npm and Node.js logos.
TypeScript

Type Inference in TypeScript

TypeScript works out most types for you. Learn how inference treats let and const, arrays, return values and callbacks, and when to write a type yourself.

7 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.