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.

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
extendsin 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 Tproduces the union ofT's keys;K extends keyof Tcombined withT[K]gives a return type that tracks the key you passed.keyofover an index signature collapses tostring | number, andkeyof {}isnever, 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,
extendsis 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
// 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
| Constraint | Guarantees inside the body | Rejects | Typical use |
|---|---|---|---|
none (T) | nothing; T is effectively unknown | nothing | pass-through and factory wrappers |
T extends object | it is not a primitive | string, number, null, undefined | object mapping helpers |
T extends Record<string, unknown> | indexable by string | interfaces without an index signature | generic deep-merge |
T extends { id: string } | id is readable as string | objects without a string id | repository helpers |
T extends keyof U | argument is one of U's keys | any other string literal | safe property access |
T extends string | string methods are available | number, symbols | template literal types |
T extends U ? X : Y | a 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
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
// 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:
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
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 runtimeThe 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
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>; // stringA 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
| Error | Message | Cause | Fix |
|---|---|---|---|
| TS2344 | Type X does not satisfy the constraint Y | a type argument outside the constraint | fix the argument, or widen the constraint |
| TS2345 | Argument of type X is not assignable to parameter of type Y | a value that fails the inferred constraint | check the property type, not just its name |
| TS2322 | Type T is not assignable to type string | unconstrained T used where a concrete type is required | add T extends string |
| TS18046 | x is of type unknown | no constraint, so nothing is known | constrain the parameter, or narrow inside |
| TS2536 | Type K cannot be used to index type T | K not constrained to keyof T | add K extends keyof T |
| TS2554 | Expected N arguments, but got M | a defaulted type parameter mistaken for a defaulted value | default the parameter, not the type |
| TS2589 | Type instantiation is excessively deep and possibly infinite | recursive conditional type without a base case | add 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 toolsSmall utilities that fit TypeScript work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related TypeScript guides
All TypeScript guidesTypeScript Generic Parameter Defaults: Syntax, Precedence, and Inference
When a default applies and when inference wins, defaults that reference earlier parameters, and how a defaulted type parameter keeps a library change non-breaking.
TypeScript Branded Types: Nominal Typing, Type Tags, and Validation
How a phantom property makes two strings incompatible, unique symbol brands, unit-typed numbers, and the places where a brand quietly disappears.
TypeScript Ambient Declarations: .d.ts Files, declare, and declare global
How declare and .d.ts files describe runtime values, wildcard modules for assets, declare global with var, and module augmentation of third-party types.
TypeScript Discriminated Unions: Exhaustiveness Checking and the never Type
Why the discriminant must be a literal, how never closes an exhaustive switch, and the duplicate-discriminant bug that lets a missing case compile.
More in TypeScript
All TypeScript guidesThe guides filed next to this one in TypeScript, in library order.