Génériques et inférence : le modèle mental d'une relation, pas d'une inconnue en TypeScript Generics and inference: the mental model of a relation, not an unknown in TypeScript

Un générique n'est pas un type qu'on ignore : c'est une relation. T relie l'entrée à la sortie et fait voyager le type, inféré au site d'appel sans rien écrire.A generic isn't a type you ignore: it's a relation. T ties the input to the output and carries the type across, inferred at the call site with nothing written.

AuteurAuthor
Ludovic Cleuet
ThèmeTopic
GénériquesGenerics
PubliéPublished

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 // any
premier<T>(xs: T[]): T | undefined
premier([1, 2, 3]) // number | undefined
Un générique relie, il n'ignore pasA generic relates, it doesn't ignoreany rompt le lienany rompt le liennumber[]✕anylien rompu : type perdulink broken: type lostexemple exécuté avec bun et vérifié par tscexample run with bun and checked by tsc
  1. 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.
  2. 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.
  3. 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.
Un générique n'est pas « un type qu'on ignore » : c'est une relation. <T> relie l'entrée à la sortie et fait voyager le type, inféré à l'appel. Un T qui n'apparaît qu'une fois ne relie rien.A generic isn't "a type you don't know": it's a relation. <T> ties the input to the output and carries the type across, inferred at the call. A T that appears only once relates nothing.

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 : TypeError

Le 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 : TypeError

The 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.

Questions fréquentesFrequently asked questions

Qu'est-ce qu'un générique en TypeScript ?What is a generic in TypeScript?

Un paramètre de type, comme T, qui relie plusieurs positions d'une signature : le même type voyage de l'entrée à la sortie.A type parameter, like T, that ties several positions of a signature: the same type travels from input to output.

Quelle différence avec any ?What is the difference with any?

any rompt le lien et désactive la vérification ; T garde le type précis et le fait voyager.any breaks the link and disables checking; T keeps the precise type and carries it across.

Faut-il écrire le type à chaque appel ?Do you have to write the type at every call?

Non : tsc infère T à partir des arguments. On n'écrit le type que quand l'inférence est ambiguë.No: tsc infers T from the arguments. You only write the type when inference is ambiguous.

Pourquoi un T utilisé une seule fois est-il suspect ?Why is a T used only once suspect?

Il ne relie rien : il n'apporte aucune garantie, et se comporte comme une assertion as déguisée.It relates nothing: it provides no guarantee, and behaves like a disguised as assertion.

Un générique existe-t-il à l'exécution ?Does a generic exist at runtime?

Non. Comme tous les types, T est effacé à la compilation : il ne coûte rien à l'exécution.No. Like all types, T is erased at compile time: it costs nothing at runtime.

TypeScriptGénériquesInférenceSystème de typesModèle mental

← Tous les articlesAll articles