Generics without the fear
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.
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.
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.
| Aspect | Value parameter | Type parameter |
|---|---|---|
| Declared | in ( ): first(xs) | in < >: first<T> |
| Given by the caller | first([1, 2]) | first<number>(...) |
| Usually | always passed | inferred from the values |
| Exists at run time | yes | no, 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.
- 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.
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.
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.
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.
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.
function create<T>(): T {return new T();}// error TS2693: 'T' only refers to a type,// but is being used as a value here.
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.