En bref. On croit qu’une union « ajoute » des possibilités, donc des champs. C’est l’inverse : elle en retire.
Le modèle en une phrase
Une union rétrécit ce qu’on peut toucher, une intersection l’élargit.
In short. You’d think a union “adds” possibilities, hence fields. It’s the opposite: it takes them away.
The model in one sentence
A union narrows what you can touch, an intersection widens it.
a.nom // sur Chat | Chien : oka.miauler() // erreur tschybride: Chat & Chien // tout est là
a.nom // sur Chat | Chien : ok— Sur une union, on ne peut toucher que ce que les deux formes partagent : ici seulement nom. Joindre les valeurs rétrécit les champs accessibles.On a union, you can only touch what both shapes share: here only nom. Joining values narrows the accessible fields.a.miauler() // erreur tsc— miauler n'existe que sur Chat : la valeur peut être un Chien, donc tsc refuse l'accès.miauler only exists on Chat: the value may be a Chien, so tsc refuses the access.hybride: Chat & Chien // tout est là— Une intersection est les deux à la fois : tous les champs sont accessibles. L'union rétrécit l'accès, l'intersection l'élargit.An intersection is both at once: every field is accessible. A union narrows access, an intersection widens it.
La preuve, avec du code qui tourne
Un chat ou un chien, puis les deux à la fois :
type Chat = { nom: string; miauler: () => string };
type Chien = { nom: string; aboyer: () => string };
const animal = (flag: boolean): Chat | Chien =>
flag ? { nom: "Mochi", miauler: () => "miaou" } : { nom: "Rex", aboyer: () => "ouaf" };
const a = animal(true);
console.log("sur A | B, champ commun :", a.nom); // seul `nom` est partagé
// @ts-expect-error miauler n'existe pas sur toute l'union
a.miauler();
console.log("sur A | B, champ propre : refusé par tsc");
// A & B : les deux à la fois, donc tous les champs
const hybride: Chat & Chien = {
nom: "Chimère", miauler: () => "miaou", aboyer: () => "ouaf",
};
console.log("sur A & B :", hybride.miauler(), hybride.aboyer());
// Pour toucher un champ propre, il faut prouver la branche
if ("miauler" in a) console.log("après `in` :", a.miauler());sur A | B, champ commun : Mochi
sur A | B, champ propre : refusé par tsc
sur A & B : miaou ouaf
après `in` : miaouSur Chat | Chien, seul nom passe, car la valeur peut être l’un ou l’autre ; miauler est refusé. Sur Chat & Chien, tous les champs sont là. Pour toucher un champ propre à une branche, il faut prouver laquelle, ici avec in (le fichier compile en strict avec tsc 6).
Ce que l’image cache
L’image simplifie les intersections : deux types qui se contredisent, par exemple string & number, donnent never, une valeur impossible. Et l’union n’est pas qu’une affaire de champs : elle sert aussi à modéliser les cas (succès ou erreur), ce que le numéro approfondit.
Pour aller plus loin
Le numéro ci-dessous détaille l’accès aux membres d’une union, les intersections impossibles et la façon de composer des formes sans surprise.
The proof, with running code
A cat or a dog, then both at once:
type Chat = { nom: string; miauler: () => string };
type Chien = { nom: string; aboyer: () => string };
const animal = (flag: boolean): Chat | Chien =>
flag ? { nom: "Mochi", miauler: () => "miaou" } : { nom: "Rex", aboyer: () => "ouaf" };
const a = animal(true);
console.log("sur A | B, champ commun :", a.nom); // only `nom` is shared
// @ts-expect-error miauler doesn't exist on the whole union
a.miauler();
console.log("sur A | B, champ propre : refusé par tsc");
// A & B: both at once, so every field
const hybride: Chat & Chien = {
nom: "Chimère", miauler: () => "miaou", aboyer: () => "ouaf",
};
console.log("sur A & B :", hybride.miauler(), hybride.aboyer());
// To touch a branch-only field, you must prove the branch
if ("miauler" in a) console.log("après `in` :", a.miauler());sur A | B, champ commun : Mochi
sur A | B, champ propre : refusé par tsc
sur A & B : miaou ouaf
après `in` : miaouOn Chat | Chien only nom passes, since the value may be either; miauler is refused. On Chat & Chien every field is there. To touch a branch-only field you must prove which branch, here with in (the file compiles in strict mode with tsc 6).
What the picture hides
The picture simplifies intersections: two types that contradict each other, such as string & number, give never, an impossible value. And a union isn’t only about fields: it also models cases (success or error), which the issue goes deeper into.
Go deeper
The issue below details member access on a union, impossible intersections and how to compose shapes without surprises.