← TypeScript

Intermediate · 10 of 16 · 13 min read

Generic constraints

What extends promises the function body, why it means "at least" rather than "exactly", and the K extends keyof T pattern you will write constantly.

  • Generic constraints

Inside a generic function the compiler knows nothing about T. A constraint is how you tell it what the body may assume, while the caller still keeps whatever precise type they passed.

The problem a constraint solves

function size<T>(item: T): number {
  // return item.length;
  // Property 'length' does not exist on type 'T'
  return 0;
}

T could be a number, null, a symbol. The compiler refuses, correctly. extends narrows what the body is allowed to assume:

function size<T extends { length: number }>(item: T): number {
  return item.length;
}

console.log(size("hello"));                     // 5
console.log(size([1, 2, 3]));                   // 3
console.log(size({ length: 9, other: true }));  // 9
// size(42); // 'number' is not assignable to '{ length: number }'

And the caller is unaffected — the argument keeps its own type, not the constraint:

function identityish<T extends string>(value: T): T { return value; }

const exact = identityish("admin"); // "admin", not string
console.log(exact);

That is the division of labour worth stating in an interview: the constraint is for the body, not for the caller.

“At least”, not “exactly”

The most common misunderstanding, and it shows up as a confusing error:

function withDefaults<T extends { id: number }>(item: T): T {
  // return { id: item.id };
  // Type '{ id: number }' is not assignable to type 'T'.
  // 'T' could be instantiated with a different subtype.
  return { ...item, id: item.id };
}

const result = withDefaults({ id: 1, name: "Ana" });
console.log(result.name); // "Ana" — still there, because the spread kept it

Promising to return T means returning everything the caller passed. The caller might have sent { id, name, email }, and { id: item.id } is not that. Either preserve the input, or stop promising T:

function onlyId<T extends { id: number }>(item: T): { id: number } {
  return { id: item.id }; // honest about returning less
}
console.log(onlyId({ id: 2, name: "Beto" }));

K extends keyof T

The pattern you will write most often. Two parameters, tied together:

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

const user = { id: 1, name: "Ana", active: true };

console.log(get(user, "id").toFixed(0));     // "1"
console.log(get(user, "name").toUpperCase()); // "ANA"
// get(user, "email"); // not assignable to '"id" | "name" | "active"'

T is the object, K is restricted to its keys, and the return T[K] is read from both. A constraint may refer to another type parameter, which is what makes this work.

The same shape, for writing and for projecting:

function set<T, K extends keyof T>(obj: T, key: K, value: T[K]): void {
  obj[key] = value;
}

function pluck<T, K extends keyof T>(items: T[], key: K): T[K][] {
  return items.map((item) => item[key]);
}

const users = [{ id: 1, name: "Ana" }, { id: 2, name: "Beto" }];
console.log(pluck(users, "name")); // ["Ana", "Beto"] — string[]

Common constraints

Constraint Means
T extends object any non-primitive
T extends Record<string, unknown> a dictionary-ish object
T extends { id: number } has at least an id
K extends keyof T a key of T
T extends unknown[] any array
T extends readonly unknown[] any array, including readonly
T extends (...args: any[]) => any any function
T extends new (...args: any[]) => any a class, not an instance
T extends string a string, and keeps the literal
type Constructor<T = object> = new (...args: any[]) => T;

function create<T>(Cls: new () => T): T { return new Cls(); }

class Service { name = "svc"; }
console.log(create(Service).name); // "svc"

function call<T extends (...args: any[]) => any>(fn: T, ...args: Parameters<T>): ReturnType<T> {
  return fn(...args);
}
console.log(call((a: number, b: number) => a + b, 1, 2)); // 3

Defaults are not constraints

They are independent, and often used together:

// Constraint only — the caller must supply something object-like:
function a<T extends object>(value: T) { return value; }

// Default only — used when nothing can be inferred:
interface Box<T = string> { value: T }

// Both:
function createStore<T extends object = Record<string, never>>(initial?: T) {
  return { state: initial };
}

const box: Box = { value: "x" };       // T defaults to string
console.log(a({ id: 1 }), box.value, createStore({ a: 1 }).state);

A constraint says what is allowed; a default says what to use when nothing was given.

Constraining to keep literals

A quiet but useful trick. Without a constraint, inference widens:

function first<T>(items: T[]): T | undefined { return items[0]; }
const a = first(["admin", "user"]);        // string | undefined

function firstLiteral<T extends string>(items: T[]): T | undefined { return items[0]; }
const b = firstLiteral(["admin", "user"]); // "admin" | "user" | undefined

console.log(a, b);

T extends string tells the compiler the literal matters, so it keeps it. From TypeScript 5.0 there is also const T, which asks for the same thing more directly:

function firstConst<const T extends readonly string[]>(items: T): T[number] {
  return items[0] as T[number];
}
console.log(firstConst(["admin", "user"])); // typed "admin" | "user"

Constraints and narrowing do not mix

A constraint is not a guard. Inside the body, T is still T:

function describe<T extends string | number>(value: T): string {
  if (typeof value === "string") {
    return value.toUpperCase(); // narrowed to T & string
  }
  return value.toFixed(2);       // narrowed to T & number
}

console.log(describe("a"), describe(1.5)); // "A" "1.50"

That works — but note the narrowed type is T & string, not string, which occasionally produces errors that read strangely. When a function needs to branch on the type, a plain union parameter is usually simpler than a constrained generic.

Common mistakes

Reading a member the constraint does not promise

Mistake. item.name inside <T extends object>. Why it fails. object promises nothing beyond being non-primitive. What to do instead. Constrain to the shape you need: <T extends { name: string }>.

Returning a new object from a function promising T

Mistake. return { id: item.id } where the signature says : T. Why it fails. T may be a subtype with more members, and the new object does not have them. What to do instead. Spread the input, or change the return type to what you actually build.

Taking key: string instead of constraining it

Mistake. function get<T>(obj: T, key: string). Why it fails. string is wider than the object’s keys, so the lookup is an implicit any and a typo is never caught. What to do instead. K extends keyof T, returning T[K].

Check yourself

3 questions from the bank on what you just read. Answering here does not affect your quiz history.

Inside a generic function the compiler only knows what the constraint promises.

Why is .length an error here?

Code sample
function size<T>(item: T): number {
  return item.length;
}

What does K extends keyof T express in get<T, K extends keyof T>(obj: T, key: K)?

A constraint says what the type parameter must include, not what it is limited to.

Why is this return rejected?

Code sample
function withDefaults<T extends { id: number }>(item: T): T {
  return { id: item.id };
}
Practise Generic constraints →

Further reading

Everything above is meant to be enough on its own. These are for when you want the full specification of a detail.

Reaching the end of a lecture marks it as read.