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[] = chiensconst f: (c: Chien) => string = nommeranimaux.push(new Animal()) // TypeError plus tard
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.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.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 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 : TypeErrorLe 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 : TypeErrorThe 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.