Skip to content

Generics without the fear

Working knowledgeConcept

A helper typed with any forgets what you gave it; one typed for number[] works only for numbers. A type parameter fixes both: it is an argument, like any other, except that it takes a type. Here is how you pass one, how the checker usually works it out for you, and how to limit what it accepts.

01 A helper that forgets what you gave it

first returns the first element of any array. Typed with any, it compiles, and the bug only shows up when it runs.

any.ts
function first(xs: any[]): any {
return xs[0];
}
const n = first([1, 2, 3]);
n.toUpperCase(); // compiles
Shell
npx tsc --noEmit --strict any.ts && node any.ts
Text
TypeError: n.toUpperCase is not a function

A real run (TypeScript 5.9, Node 24, which runs .ts files by stripping the types). The checker had nothing to say, because any switches checking off. You could write firstNumber, firstString and so on, but then the same three lines exist once per type. What you want is a first whose return type follows its argument.

02 A type parameter is an argument for types

Angle brackets after the name declare a type parameter. Inside the function, T stands for whatever type the caller uses, just as xs stands for whatever array they pass.

first.ts
function first<T>(xs: T[]): T | undefined {
return xs[0];
}
const n = first([1, 2, 3]); // T = number
const s = first(['a', 'b']); // T = string
const e = first<number>([]); // T given by hand
n?.toUpperCase();
Text
first.ts(8,4): error TS2339: Property 'toUpperCase' does not exist on type 'number'.

Same three lines of code, but now the bug is a compile error (a real tsc run). The return type is T | undefined because an empty array has no first element.

Value parameters and type parameters work the same way
AspectValue parameterType parameter
Declaredin ( ): first(xs)in < >: first<T>
Given by the callerfirst([1, 2])first<number>(...)
Usuallyalways passedinferred from the values
Exists at run timeyesno, it is erased

03 How the checker works out T for you

You rarely write <number> by hand. The checker infers type arguments by matching the types of the values you pass against the parameter types. A function with two type parameters shows how it goes, in order.

map.ts
function map<T, U>(xs: T[], f: (x: T) => U): U[] {
const out: U[] = [];
for (const x of xs) out.push(f(x));
return out;
}
const labels = map([1, 2, 3], (n) => n.toFixed(1));
const check: number = labels; // ask the checker what labels is
How the checker fills in T and U
Step 1 of 6
map’s parameters
xs: T[]
f: (x: T) => U
returns U[]
This call’s arguments
[1, 2, 3]
(n) => n.toFixed(1)
labels
What the checker has worked out
Empty
  • being matched
  • set aside for now
  • just inferred
  • the result

The checker meets map([1, 2, 3], (n) => n.toFixed(1)). Nobody wrote <number, string>, so T and U are unknown and must be inferred from the arguments.

Text
map.ts(8,7): error TS2322: Type 'string[]' is not assignable to type 'number'.

The last line of map.ts was there only to make the checker say what it inferred, and the real error confirms string[]. Assigning to a wrong type, or hovering in your editor, is the quickest way to see an inferred type.

04 Constraints: extends limits what T can be

Inside first<T>, you can do almost nothing with a T, because it could be anything. To use .length, promise the checker that every T has one, with extends. Callers must then pass a type that fits.

TypeScript
function longest<T extends { length: number }>(a: T, b: T): T {
return a.length >= b.length ? a : b;
}
longest('abc', 'de'); // T = "abc" | "de"
longest([1, 2], [3]); // T = number[]
longest(10, 20);
Text
error TS2345: Argument of type 'number' is not assignable to parameter of type '{ length: number; }'.

A constraint can refer to another type parameter. K extends keyof T says: K must be one of T’s keys. The return type T[K] then looks up the type of that one property.

TypeScript
function get<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}
const user = { name: 'Ana', age: 31 };
get(user, 'age'); // number
get(user, 'name'); // string
get(user, 'email');
Text
error TS2345: Argument of type '"email"' is not assignable to parameter of type '"name" | "age"'.

Both errors are real tsc output. Note the first comment: from two string literals the checker infers the literal types "abc" | "de" rather than string. Both are strings, so the result still works anywhere a string does.

05 Generic types: Box<T>, Array<T>, Promise<T>

Interfaces, type aliases and classes take type parameters too. You have used them already: string[] is short for Array<string>, an async function returns a Promise<T>, and Map<K, V> has two. A parameter may have a default, used when the caller leaves it out.

box.ts
interface Box<T> {
value: T;
}
type Pair<A, B = A> = [A, B];
const age: Box<number> = { value: 31 };
const point: Pair<number> = [3, 4]; // B defaults to number
const tag: Pair<string, number> = ['id', 7];
const cache = new Map<string, Box<number>>();
const bad: Box<number> = { value: '31' };
Text
box.ts(10,28): error TS2322: Type 'string' is not assignable to type 'number'.

For types, inference does less: on a variable annotation you must write the arguments (Box<number>), while for new Map<string, …>() and function calls the checker can often infer them from what you pass in.

06 T is gone when the code runs

Type parameters are part of the type system only. The compiled JavaScript for first is function first(xs) { return xs[0]; }, with no T anywhere. So you cannot ask a type parameter anything at run time: new T(), typeof T or x instanceof T do not compile.

Needs T at run time
function create<T>(): T {
return new T();
}
// error TS2693: 'T' only refers to a type,
// but is being used as a value here.
Pass the value instead
function create<T>(ctor: new () => T): T {
return new ctor();
}
class User { name = 'new user'; }
const u = create(User); // u: User

If the code needs to know the type, pass a value that carries it: a constructor, a validator, a tag. What TypeScript checks, and what it erases goes into erasure in full.

07 When a generic is a lie

function parse<T>(json: string): T { return JSON.parse(json); } const u = parse<{ name: string }>('{"nmae":"Ana"}'); u.name.toUpperCase(); // crashesT only in the return typeNothing about the arguments decides T, so the caller simply picks one and nothing checks it. This is a cast in disguise. Return unknown and validate, or take a validator as a parameter.
function log<T>(x: T): void { console.log(x); }A type parameter used onceT links nothing to anything. x: unknown says the same and is easier to read. A type parameter earns its place when it appears at least twice, e.g. in a parameter and in the return type.
function same<T>(a: T, b: T) { return a === b; } same(1, 'a'); // Argument of type 'string' is not // assignable to parameter of type 'number'.The first argument decidesThe checker inferred T = number from 1 and then rejected 'a'. Write same<number | string>(1, 'a') if mixing is meant, or use two parameters A and B.
const id = <T,>(x: T) => x;Generic arrows in .tsx filesIn a .tsx file, <T> before an arrow function is read as a JSX tag. Write <T,> or <T extends unknown>.

as T inside a generic function silences the checker for every caller at once. If you need it, the signature is probably promising more than the code can check.

08 Check yourself

Question

function wrap<T>(x: T): T[] { return [x]; } What is the type of wrap(true)?

Question

Why does function len<T>(x: T) { return x.length; } fail to compile?

Question

function create<T>(): T { return new T(); } is rejected. Why?

09 Practise this

Was this tutorial useful?Your vote tells us what to improve next.
Spotted a mistake, or something unclear?