La variance : le modèle mental du sens de la substitution en TypeScript Variance: the mental model of the direction of substitution in TypeScript

La variance dit dans quel sens un type peut en remplacer un autre : plus précis pour ce qu'on produit, plus large pour ce qu'on consomme. Lire et écrire n'a pas de bon sens.Variance says in which direction one type can replace another: more precise for what you produce, wider for what you consume. Reading and writing has no good direction.

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

En bref. Un chien est un animal. Mais un tableau de chiens est-il un tableau d’animaux, et une fonction d’animaux, une fonction de chiens ?

Le modèle en une phrase

La variance dit dans quel sens on peut substituer : plus précis pour ce qu’on produit, plus large pour ce qu’on consomme.

In short. A dog is an animal. But is an array of dogs an array of animals, and a function of animals a function of dogs?

The model in one sentence

Variance says in which direction you can substitute: more precise for what you produce, wider for what you consume.

const animaux: Animal[] = chiens
const f: (c: Chien) => string = nommer
animaux.push(new Animal()) // TypeError plus tard
Le sens de la substitutionThe direction of substitutioncovariant : on lit, ça passecovariant : on lit, ça passeChien[]→Animal[]substitution permisesubstitution allowedexemple exécuté avec bun et vérifié par tscexample run with bun and checked by tsc
  1. const animaux: Animal[] = chiens — Ce qu'on produit peut être plus précis : un tableau de Chien se lit comme un tableau d'Animal.What you produce may be more precise: an array of Chien reads as an array of Animal.
  2. const f: (c: Chien) => string = nommer — Ce qu'on consomme s'inverse : une fonction qui accepte Animal sert là où on attend une fonction de Chien.What you consume reverses: a function that accepts Animal serves where a function of Chien is expected.
  3. animaux.push(new Animal()) // TypeError plus tard — Mais la covariance ne protège pas l'écriture : un Animal entre dans un tableau de Chien, et le code plante plus tard.But covariance doesn't protect writing: an Animal enters an array of Chien, and the code crashes later.
La variance dit dans quel sens on peut substituer un type à un autre. Ce qu'on produit peut être plus précis (covariance), ce qu'on consomme doit être plus large (contravariance), et une position qui lit et écrit à la fois n'a pas de bon sens.Variance says in which direction one type can be substituted for another. What you produce can be more precise (covariance), what you consume must be wider (contravariance), and a position that both reads and writes has no good direction.

La preuve, avec du code qui tourne

Une lecture, un paramètre, un refus, et un piège sur l’écriture :

class Animal { nom = "animal"; }
class Chien extends Animal { aboyer() { return "ouaf"; } }

// Lecture (covariant) : un tableau de Chien peut servir de tableau d'Animal.
const chiens: Chien[] = [new Chien()];
const animaux: Animal[] = chiens;
console.log(animaux[0].nom);

// Écriture (contravariant) : une fonction qui accepte Animal accepte aussi un Chien.
const nommer = (a: Animal) => a.nom;
const surChien: (c: Chien) => string = nommer;
console.log(surChien(new Chien()));

// L'inverse est refusé : une fonction qui exige un Chien ne peut pas recevoir un Animal.
const aboyer = (c: Chien) => c.aboyer();
// @ts-expect-error  (c: Chien) n'est pas assignable à (a: Animal) en strict
const surAnimal: (a: Animal) => string = aboyer;

// Le piège : la covariance des tableaux laisse écrire un Animal dans un tableau de Chien.
animaux.push(new Animal());
try { console.log(chiens[1].aboyer()); }
catch (e) { console.log("covariance + écriture :", (e as Error).constructor.name); }
animal
animal
covariance + écriture : TypeError

Le fichier compile en strict avec tsc 6. Un tableau de Chien est accepté comme tableau d’Animal. Une fonction qui accepte un Animal est acceptée là où une fonction de Chien est attendue, mais l’inverse est refusé, ts-expect-error le prouve. Enfin, la covariance des tableaux laisse pousser un Animal parmi des Chiens, et l’appel d’aboyer plante avec un TypeError.

Ce que l’image cache

TypeScript est volontairement permissif sur les tableaux, par commodité : c’est un compromis connu, pas une preuve de sûreté. Les modificateurs in et out sur les paramètres de type permettent de dire explicitement le sens voulu. En pratique, la règle est de ne pas mélanger lecture et écriture sur un même type paramétré.

Pour aller plus loin

Le numéro ci-dessous détaille covariance, contravariance, invariance, et les modificateurs in et out sur les paramètres de type.

The proof, with running code

A read, a parameter, a refusal, and a trap on writing:

class Animal { nom = "animal"; }
class Chien extends Animal { aboyer() { return "ouaf"; } }

// Reading (covariant): an array of Chien can serve as an array of Animal.
const chiens: Chien[] = [new Chien()];
const animaux: Animal[] = chiens;
console.log(animaux[0].nom);

// Writing (contravariant): a function that accepts Animal also accepts a Chien.
const nommer = (a: Animal) => a.nom;
const surChien: (c: Chien) => string = nommer;
console.log(surChien(new Chien()));

// The reverse is refused: a function that requires a Chien can't receive an Animal.
const aboyer = (c: Chien) => c.aboyer();
// @ts-expect-error  (c: Chien) n'est pas assignable à (a: Animal) en strict
const surAnimal: (a: Animal) => string = aboyer;

// The trap: array covariance lets you write an Animal into an array of Chien.
animaux.push(new Animal());
try { console.log(chiens[1].aboyer()); }
catch (e) { console.log("covariance + write:", (e as Error).constructor.name); }
animal
animal
covariance + écriture : TypeError

The file compiles in strict mode with tsc 6. An array of Chien is accepted as an array of Animal. A function that accepts an Animal is accepted where a function of Chien is expected, but the reverse is refused, ts-expect-error proves it. Finally, array covariance lets you push an Animal among Chiens, and the call to aboyer crashes with a TypeError.

What the picture hides

TypeScript is deliberately permissive on arrays, for convenience: it’s a known trade-off, not a proof of safety. The in and out modifiers on type parameters let you state the intended direction explicitly. In practice the rule is not to mix reading and writing on the same parameterized type.

Go deeper

The issue below details covariance, contravariance, invariance, and the in and out modifiers on type parameters.

Questions fréquentesFrequently asked questions

Qu'est-ce que la variance ?What is variance?

La règle qui dit si un type paramétré peut en remplacer un autre quand ses paramètres sont plus précis ou plus larges.The rule that says whether a parameterized type can replace another when its parameters are more precise or wider.

Qu'est-ce que la covariance ?What is covariance?

Le sens naturel : ce qu'on produit ou lit peut être plus précis. Un tableau de Chien se lit comme un tableau d'Animal.The natural direction: what you produce or read can be more precise. An array of Chien reads as an array of Animal.

Qu'est-ce que la contravariance ?What is contravariance?

Le sens inverse pour ce qu'on consomme : une fonction qui accepte Animal peut servir là où on attend une fonction de Chien.The reverse direction for what you consume: a function that accepts Animal can serve where a function of Chien is expected.

Pourquoi les tableaux sont-ils un piège ?Why are arrays a trap?

Parce qu'ils sont covariants alors qu'on peut y écrire : on peut pousser un Animal dans ce qui est typé tableau de Chien.Because they are covariant while you can also write to them: you can push an Animal into what is typed as an array of Chien.

À quoi servent in et out ?What are in and out for?

À déclarer explicitement le sens d'un paramètre de type : out pour ce qu'on produit, in pour ce qu'on consomme.To explicitly declare the direction of a type parameter: out for what you produce, in for what you consume.

TypeScriptVarianceCovarianceContravarianceModèle mental

← Tous les articlesAll articles