En bref. On lit souvent un générique comme un type qu’on ne connaît pas encore. Ce n’est pas ce qu’il fait.
Le modèle en une phrase
Un générique est une relation : T relie l’entrée à la sortie et fait voyager le type, sans rien écrire au site d’appel.
In short. A generic is often read as a type you don’t know yet. That’s not what it does.
The model in one sentence
A generic is a relation: T ties the input to the output and carries the type across, with nothing written at the call site.
premierAny(xs: any[]): any // anypremier<T>(xs: T[]): T | undefinedpremier([1, 2, 3]) // number | undefined
premierAny(xs: any[]): any // any— Avec any, la sortie ne dépend plus de l'entrée : le type est perdu en chemin.With any, the output no longer depends on the input: the type is lost along the way.premier<T>(xs: T[]): T | undefined— Avec T, la même lettre apparaît des deux côtés : c'est une relation, pas un type ignoré.With T, the same letter appears on both sides: it's a relation, not an ignored type.premier([1, 2, 3]) // number | undefined— Au site d'appel, tsc infère T = number sans rien écrire, et la sortie porte ce type.At the call site, tsc infers T = number with nothing written, and the output carries that type.
La preuve, avec du code qui tourne
La même fonction avec any, puis avec un paramètre de type :
// any rompt le lien entre l'entrée et la sortie :
function premierAny(xs: any[]): any { return xs[0]; }
// <T> le garde : le type d'entrée voyage jusqu'à la sortie.
function premier<T>(xs: T[]): T | undefined { return xs[0]; }
const a = premierAny([1, 2, 3]); // any
const b = premier([1, 2, 3]); // number | undefined (inféré, rien écrit)
const c = premier(["x", "y"]); // string | undefined
console.log(a, b, c);
try {
// @ts-expect-error b est number | undefined : toUpperCase n'existe pas
b.toUpperCase();
} catch (e) { console.log("le lien tient :", (e as Error).constructor.name); }1 1 x
le lien tient : TypeErrorLe fichier compile en strict avec tsc 6. Avec any, la sortie est any quel que soit le tableau passé. Avec T, tsc infère number pour le premier appel et string pour le second, sans annotation. Appeler toUpperCase sur le premier résultat est refusé à la compilation, ts-expect-error le prouve.
Ce que l’image cache
Un T n’a de sens que s’il apparaît à au moins deux endroits : s’il n’apparaît qu’une fois, il ne relie rien et se comporte comme un as déguisé en chevrons. L’inférence a aussi ses limites : sur un appel ambigu, elle choisit le type le plus large, et il faut alors guider la signature.
Pour aller plus loin
Le numéro ci-dessous détaille la relation que porte T, l’inférence au site d’appel et le piège du T qui n’apparaît qu’une fois.
The proof, with running code
The same function with any, then with a type parameter:
// any breaks the link between input and output:
function premierAny(xs: any[]): any { return xs[0]; }
// <T> keeps it: the input type travels to the output.
function premier<T>(xs: T[]): T | undefined { return xs[0]; }
const a = premierAny([1, 2, 3]); // any
const b = premier([1, 2, 3]); // number | undefined (inferred, nothing written)
const c = premier(["x", "y"]); // string | undefined
console.log(a, b, c);
try {
// @ts-expect-error b est number | undefined : toUpperCase n'existe pas
b.toUpperCase();
} catch (e) { console.log("the link holds:", (e as Error).constructor.name); }1 1 x
le lien tient : TypeErrorThe file compiles in strict mode with tsc 6. With any, the output is any whatever array is passed. With T, tsc infers number for the first call and string for the second, with no annotation. Calling toUpperCase on the first result is refused at compile time, ts-expect-error proves it.
What the picture hides
A T only makes sense if it appears in at least two places: if it appears once, it relates nothing and behaves like an as dressed up in brackets. Inference also has limits: on an ambiguous call it picks the widest type, and you must then guide the signature.
Go deeper
The issue below details the relation T carries, inference at the call site and the trap of a T that appears only once.