Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

TypeScript Generics: Type Constraints, extends Keyof, and Default Types

What T extends really constrains, how K extends keyof T keeps a return type tied to the key you pass, defaults on type parameters, and where NoInfer stops a second argument from widening inference.

~6 min readTypeScript
#TypeScript#Generics#Type System
Modular type blocks locking into constrained keyof slots with glowing alignment lines

A generic constraint is the part of a generic signature that keeps the type parameter usable. Without one, T is unknown inside the function body: you cannot read a property, call a method, or index anything on it. T extends { id: string } promises that every instantiation has an id, and K extends keyof T promises that a key argument actually indexes the object it is paired with. The same extends keyword, used inside a conditional type, means something else entirely — that split is where most of the confusion around generics comes from.

Quick Summary

  • extends in a type parameter list means "assignable to". It is a constraint, not inheritance, and it accepts interfaces, unions, and object literal shapes.
  • A constraint is checked at the call, so a bad argument fails at the argument rather than inside the function body.
  • keyof T produces the union of T's keys; K extends keyof T combined with T[K] gives a return type that tracks the key you passed.
  • keyof over an index signature collapses to string | number, and keyof {} is never, which makes some generic helpers legal only on objects with declared keys.
  • Type parameters can declare defaults (<T extends Element = HTMLDivElement>), which makes them optional at the call site but not at the declaration.
  • Inside a conditional type, extends is a test, and a naked type parameter on the left distributes over unions — a different rule with different results.
  • Code that reads like it constrains a value (Record<K, V>, Pick<T, K>) is constraining a type argument; runtime validation is a separate problem that generics never solve.

Basic syntax and type signatures

typescript
// A property-shaped constraint. function pluck<T, K extends keyof T>(items: T[], key: K): T[K][] { return items.map((item) => item[key]); } const users = [{ id: 1, name: "ada" }, { id: 2, name: "alan" }]; const names = pluck(users, "name"); // string[] const ids = pluck(users, "id"); // number[] // pluck(users, "email"); // TS2345: not assignable to "id" | "name" // A structural constraint that two unrelated types satisfy. function longest<T extends { length: number }>(a: T, b: T): T { return a.length >= b.length ? a : b; } longest("hello", "hi"); // string longest([1, 2, 3], [4]); // number[] longest({ length: 2 }, { length: 5 }); // { length: number } // Defaults make the parameter optional at the call site. type Wrapper<T extends object = Record<string, unknown>> = { value: T; at: Date; }; type Loose = Wrapper; // Wrapper<Record<string, unknown>> type Strict = Wrapper<{ id: string }>; // Wrapper<{ id: string }> // keyof typeof reads the keys of a value, not of a type. const ROUTES = { home: "/", posts: "/posts", about: "/about" } as const; type RouteName = keyof typeof ROUTES; // "home" | "posts" | "about" type RoutePath = (typeof ROUTES)[RouteName]; // "/" | "/posts" | "/about"

K extends keyof T is doing two jobs: it rejects keys that T does not have, and it keeps K as the specific literal the caller passed so T[K] resolves to one property type rather than a union of all of them. If the parameter were typed key: keyof T instead, T[K] would be unavailable, and the return type would have to be T[keyof T][], a union of every value type in the object.

Constraint placement matters for inference. T is inferred from the argument; K is inferred from the literal "name", and the constraint then verifies it. If no argument determines K, or the constraint is too specific for inference to land on it, TypeScript falls back to the constraint itself, and the return type silently widens to the default.

Constraint forms side by side

ConstraintGuarantees inside the bodyRejectsTypical use
none (T)nothing; T is effectively unknownnothingpass-through and factory wrappers
T extends objectit is not a primitivestring, number, null, undefinedobject mapping helpers
T extends Record<string, unknown>indexable by stringinterfaces without an index signaturegeneric deep-merge
T extends { id: string }id is readable as stringobjects without a string idrepository helpers
T extends keyof Uargument is one of U's keysany other string literalsafe property access
T extends stringstring methods are availablenumber, symbolstemplate literal types
T extends U ? X : Ya conditional test, not a constraint—distributive type logic
T extends any (in a conditional)nothing; it only turns on distribution—per-union-member mapping

The Record<string, unknown> row surprises people: a type alias for an interface with known properties is not assignable to Record<string, unknown> in older TypeScript versions, because an interface can be augmented later and therefore has no implicit index signature. A type alias with the same body is assignable. Since TypeScript 4.4, symbols and template literal patterns widened the rule slightly, but the interface-versus-type-alias difference still bites when a generic helper takes Record<string, unknown> and the caller passes an interface.

Practical edge cases and deep dives

1. keyof on index signatures, unions, and empty objects

typescript
type Dict = { [key: string]: number }; type DictKeys = keyof Dict; // string | number type Union = { a: 1 } | { b: 2 }; type UnionKeys = keyof Union; // never -- keys common to all members type Empty = keyof {}; // never type Tuple = keyof [string, number]; // number | "0" | "1" | "length" | ...

keyof of an index signature is string | number because JavaScript coerces numeric keys to strings, so both are valid lookups. keyof of a union is the intersection of the members' keys, so two object types with no shared property give never and any K extends keyof Union helper is unusable on that union — the fix is usually to distribute the generic over the union with a conditional type rather than to loosen the constraint.

keyof {} being never also explains why Pick<T, never> is {} and why a generic function constrained to keyof T with T = {} accepts no key argument at all. That is a type error worth reading carefully: the constraint is not broken, the type simply has nothing to offer.

2. Defaults, NoInfer, and keeping inference from leaking

typescript
// The default applies when the argument list does not determine T. function createElement<T extends HTMLElement = HTMLDivElement>( tag: string, init?: Partial<T> ): T { return Object.assign(document.createElement(tag), init) as T; } const div = createElement("div"); // HTMLDivElement const input = createElement<HTMLInputElement>("input"); // HTMLInputElement // NoInfer (TypeScript 5.4) stops one argument from widening the inferred type. function select<T, K extends keyof T>(items: T[], key: NoInfer<K>): T[K][] { return items.map((item) => item[key]); }

Without NoInfer, a second argument of the same type parameter can pull inference toward the wrong candidate: given function pair<T>(a: T, b: T), calling pair({ id: 1 }, { id: 2, name: "x" }) infers T as the union or as the wider object depending on ordering, and the error lands on the wrong argument. NoInfer<T> on the position that should not drive inference keeps the type anchored to the first argument and reports the mismatch where the caller can see it. Before 5.4 the same effect required a helper (type NoInfer<T> = [T][T extends any ? 0 : never]), which is why it appears in older codebases.

Defaults on generic classes are more common than on functions, because a class argument list is written by the caller rather than inferred:

typescript
class Cache<K extends string = string, V = unknown> { private store = new Map<K, V>(); get(key: K): V | undefined { return this.store.get(key); } set(key: K, value: V): this { this.store.set(key, value); return this; } } const byId = new Cache<`user:${number}`, { name: string }>();

3. Constraints that are checked at the call, and assertions that are not

typescript
type HasId = { id: string }; function dedupe<T extends HasId>(items: T[]): T[] { const seen = new Set<string>(); return items.filter((item) => { if (seen.has(item.id)) return false; seen.add(item.id); return true; }); } dedupe([{ id: "a" }, { id: "b" }]); // ok dedupe([{ id: 1 }]); // TS2345: number is not string dedupe([{ id: "a" }] as { id: number }[]); // compiles: the cast lied // A JSON boundary: the constraint does not validate anything at runtime. function parseJson<T extends object>(text: string): T { return JSON.parse(text) as T; // assertion, not a check } const broken = parseJson<{ count: number }>('{"count":"many"}'); broken.count.toFixed(2); // TypeError at runtime

The first three calls show the value of a constraint: the mistake is caught at the argument, with the property named. The fourth shows its limit: as overrides the check, and the constraint has nothing to say about it. Generics are erased at runtime, so any check that must hold for real data has to be written as runtime code (a schema validator, a predicate, or a hand-written guard) that the generic type then describes. A parseJson<T> signature without validation is a typed promise the program cannot keep.

4. The same extends inside a conditional type

typescript
type IsString<T> = T extends string ? true : false; type A = IsString<"x" | 1>; // boolean -- distributed over the union type B = IsString<never>; // never type C = [string | 1] extends [string] ? true : false; // false type Flatten<T> = T extends (infer U)[] ? U : T; type D = Flatten<string[]>; // string type E = Flatten<string>; // string

A conditional type with a naked type parameter on the left distributes: the union is split, each member is tested, and the results are re-unioned. That is why IsString<"x" | 1> is boolean rather than false. Wrapping both sides in a tuple ([T] extends [string]) turns distribution off, which is the standard way to test a whole union at once. never distributes to never because there are no members to test — a frequent surprise when a helper returns never and the error message mentions the union instead of the empty type.

Common mistakes and compiler errors

ErrorMessageCauseFix
TS2344Type X does not satisfy the constraint Ya type argument outside the constraintfix the argument, or widen the constraint
TS2345Argument of type X is not assignable to parameter of type Ya value that fails the inferred constraintcheck the property type, not just its name
TS2322Type T is not assignable to type stringunconstrained T used where a concrete type is requiredadd T extends string
TS18046x is of type unknownno constraint, so nothing is knownconstrain the parameter, or narrow inside
TS2536Type K cannot be used to index type TK not constrained to keyof Tadd K extends keyof T
TS2554Expected N arguments, but got Ma defaulted type parameter mistaken for a defaulted valuedefault the parameter, not the type
TS2589Type instantiation is excessively deep and possibly infiniterecursive conditional type without a base caseadd a termination condition

Two habits prevent most of these. First, constrain to the smallest structural shape the body actually needs ({ id: string }, not Record<string, unknown>), because a narrower constraint both documents the requirement and keeps unrelated types out. Second, when a constraint error appears at a call site, read the message from the innermost generic outward: TypeScript prints the failing member, and the member name is almost always the real problem.

Try matching browser tools

All tools

Small utilities that fit TypeScript work — they run entirely in this browser tab, so nothing you paste leaves your device.

All TypeScript guides

More in TypeScript

All TypeScript guides

The guides filed next to this one in TypeScript, in library order.