Generics in TypeScript: Functions, Classes and Constraints
Write one function or class that works for many types and still keeps them exact. Learn type parameters, inference, generic classes, constraints and mistakes.

A function that returns the first element of an array should work for an array of numbers, an array of strings and an array of orders. Writing it three times is wasteful. Writing it once with any loses the type of what comes out. Generics solve the problem: you declare a type parameter, a placeholder that stands for whatever type the caller uses, and the compiler fills it in for each call and keeps the relationship between input and output. This post covers generic functions, how inference picks the type, generic interfaces and classes, constraints that limit what a type parameter can be, and the mistakes that make generics harder to read than they need to be. It uses TypeScript 6.x, and the reference is the handbook chapter on generics.
A generic function
A type parameter is written in angle brackets after the function name. It can then be used in the parameter types, the return type and the body.
function first<T>(items: T[]): T | undefined {
return items[0];
}
console.log(first([3, 1, 2]));
console.log(first(["north", "south"]));
console.log(first([]));3
north
undefinedThe T is chosen separately for each call. In the first call, T is number, so the result has type number | undefined. In the second, it is string. Nothing was declared at the call site, because the compiler infers T from the argument: the array of numbers matches T[], so T is number. The relationship between the argument and the result is what any throws away and what a generic keeps.
You may also pass the type explicitly, which is occasionally useful and often a sign that inference had too little to work with. If the explicit type disagrees with the argument, the compiler reports it.
function first<T>(items: T[]): T | undefined {
return items[0];
}
const words = ["a", "b"];
const n = first<number>(words);explicit.ts(6,25): error TS2345: Argument of type 'string[]' is not assignable to parameter of type 'number[]'.Several type parameters
A function can have more than one type parameter when the types are independent. By convention, single letters such as T, K and V are used for simple cases, and descriptive names such as TItem or TKey when the meaning is not obvious.
function pair<A, B>(left: A, right: B): [A, B] {
return [left, right];
}
function mapValues<K extends string, V, R>(
record: Record<K, V>,
transform: (value: V) => R,
): Record<K, R> {
const result = {} as Record<K, R>;
for (const key of Object.keys(record) as K[]) {
result[key] = transform(record[key]);
}
return result;
}
console.log(pair("id", 7));
console.log(mapValues({ ada: 36, grace: 45 }, (age) => `${age} years`));[ 'id', 7 ]
{ ada: '36 years', grace: '45 years' }mapValues carries three type parameters: the keys, the original values and the transformed values. The result has the same keys as the input and the new value type, so result.ada is a string, and result.unknown is an error. This is the typical payoff: the output type is computed from the input type, which no single concrete signature could express.
Generic interfaces and type aliases
Types can take parameters too. This is how you describe a container or a response whose payload varies.
interface Box<T> {
value: T;
map<U>(transform: (value: T) => U): Box<U>;
}
function box<T>(value: T): Box<T> {
return {
value,
map: (transform) => box(transform(value)),
};
}
const length = box("typescript").map((text) => text.length);
console.log(length.value);10Notice that map has its own type parameter U, separate from the interface's T. The interface says how its values are shaped, and each method can introduce more parameters for its own call. After map, the box holds a number, and the compiler tracks that without any annotation.
A type alias works the same way, and the standard library is full of generic aliases. Promise<T>, Array<T>, Record<K, V> and Partial<T> are all generics that you use every day.
Generic classes
A class can declare type parameters on its name, and then use them in properties and methods. Each instance fixes the parameter when it is created.
export class Stack<T> {
private items: T[] = [];
push(item: T): void {
this.items.push(item);
}
pop(): T | undefined {
return this.items.pop();
}
get size(): number {
return this.items.length;
}
}
const numbers = new Stack<number>();
numbers.push(1);
numbers.push(2);
console.log(numbers.pop());
console.log(numbers.size);2
1A Stack<number> accepts and returns numbers, and a Stack<string> strings, from one declaration. The compiler enforces it at the call sites.
import { Stack } from "./stack.js";
const numbers = new Stack<number>();
numbers.push("three");stack-misuse.ts(4,14): error TS2345: Argument of type 'string' is not assignable to parameter of type 'number'.Static members of a generic class cannot refer to the class's type parameters, because statics belong to the class and not to an instance. If a static factory needs a type, give the method its own type parameter.
Constraints: when T needs to be something
An unconstrained type parameter could be anything, so the body of the function may do nothing that works only for some types. The compiler enforces that.
function longest<T>(a: T, b: T): T {
return a.length >= b.length ? a : b;
}longest.ts(2,12): error TS2339: Property 'length' does not exist on type 'T'.
longest.ts(2,24): error TS2339: Property 'length' does not exist on type 'T'.The fix is a constraint: T extends { length: number } says that whatever T is, it must have a numeric length. Strings and arrays qualify, and so does any object you write that has one.
function longest<T extends { length: number }>(a: T, b: T): T {
return a.length >= b.length ? a : b;
}
console.log(longest("generic", "type"));
console.log(longest([1, 2, 3], [4, 5]));
console.log(longest({ length: 2, label: "short" }, { length: 9, label: "long" }));generic
[ 1, 2, 3 ]
{ length: 9, label: 'long' }The return type is still T, so the caller gets back the same specific type that went in, and not a bare { length: number }. That detail is the main reason to use a constrained generic in place of a function that takes the constraint type directly. The next posts in this series cover constraints, defaults and const type parameters in detail.
How inference chooses
The compiler infers a type parameter from every place it appears in the arguments. When it finds several candidates it takes the best common type, and when it finds conflicting ones it reports an error at the argument that disagrees.
function same<T>(a: T, b: T): T {
return a;
}
same("a", "b");
same(1, "b");conflict.ts(6,9): error TS2345: Argument of type 'string' is not assignable to parameter of type 'number'.For the first call, both candidates are string literals and T becomes string. For the second, the first argument fixed T as number, so the second argument is the one in error. When this message surprises you, the cause is usually a type parameter used for two arguments that were meant to be independent. Use two parameters, A and B, if the arguments may differ.
Mistakes that make generics worse
The most common mistake is a type parameter that appears only once. A signature such as function log<T>(value: T): void has no relationship to preserve, so T carries nothing, and (value: unknown) says the same thing more simply. A type parameter earns its place by appearing at least twice: once to receive information and once to carry it to the output.
The second mistake is reaching for generics where a union is clearer. If a function accepts a string or a number and returns a string, a pair of overloads or a union parameter is easier to read than a generic with a conditional return type.
The third is extra parameters with defaults the caller never changes, which belong to the next topic in this series. Each type parameter is a concept the reader must hold in mind, so add one only when it connects two positions in the signature.
Finally, casts inside generic functions deserve suspicion. The {} as Record<K, R> in mapValues above is a deliberate and common case, because an empty object cannot be proven to have every key until the loop completes. When you write one, keep it as small as possible and put the function behind a typed signature so callers never see it.
Testing generic code
A generic function is tested like any other, with the added point that the types are the behaviour. Run a few values of different types through it at runtime, and add compile-time assertions that the result type is what you expect.
import { deepStrictEqual } from "node:assert/strict";
import { first } from "./first.js";
deepStrictEqual(first([3, 1, 2]), 3);
deepStrictEqual(first(["north"]), "north");
deepStrictEqual(first([]), undefined);
const label: string | undefined = first(["a"]);
console.log(label);aThe last two lines are a type test as well as a runtime one: if the signature were changed to return unknown, the assignment to string | undefined would stop compiling, and the build would catch the regression.


