Unions et intersections : le modèle mental de la composition des formes en TypeScript Unions and intersections: the mental model of composing shapes in TypeScript

A | B est l'un ou l'autre, A & B les deux à la fois. Sur une union, on ne touche que ce que les deux formes partagent : la composition se lit à l'envers de l'intuition.A | B is one or the other, A & B is both at once. On a union you can only touch what both shapes share: composition reads backwards from intuition.

AuteurAuthor
Ludovic Cleuet
ThèmeTopic
Typage structurelStructural typing
PubliéPublished

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 : ok
a.miauler() // erreur tsc
hybride: Chat & Chien // tout est là
Composer des formesComposing shapesA | B : le commun seulementA | B : le commun seulementnompartagésharedmiaulerpropre à une brancheone branch onlyaboyerpropre à une brancheone branch only1 champ(s) accessible(s)1 accessible field(s)exemple exécuté avec bun et vérifié par tscexample run with bun and checked by tsc
  1. 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.
  2. 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.
  3. 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.
Une union A | B est « l'un ou l'autre » : on ne peut toucher que ce que les deux partagent. Une intersection A & B est « les deux » : tous les champs sont là. La composition se lit à l'envers de l'intuition.A union A | B is "one or the other": you can only touch what both share. An intersection A & B is "both": every field is there. Composition reads backwards from intuition.

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` : miaou

Sur 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` : miaou

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

Questions fréquentesFrequently asked questions

Que signifie A | B en TypeScript ?What does A | B mean in TypeScript?

Une union : la valeur est de type A ou de type B. On ne peut utiliser sans preuve que ce que les deux types ont en commun.A union: the value is of type A or type B. Without proof you can only use what both types have in common.

Pourquoi ne puis-je pas appeler miauler() sur Chat | Chien ?Why can't I call miauler() on Chat | Chien?

Parce que la valeur peut être un Chien, qui n'a pas miauler. tsc refuse tout accès qui pourrait échouer à l'exécution.Because the value may be a Chien, which has no miauler. tsc refuses any access that could fail at runtime.

Que signifie A & B ?What does A & B mean?

Une intersection : la valeur est de type A et de type B à la fois, donc elle porte tous les champs des deux.An intersection: the value is of type A and type B at once, so it carries all the fields of both.

Comment accéder à un champ propre à une branche d'une union ?How do you access a branch-only field of a union?

En prouvant la branche, par exemple avec l'opérateur in : après "miauler" in a, tsc sait que a est un Chat.By proving the branch, for example with the in operator: after "miauler" in a, tsc knows a is a Chat.

Que donne string & number ?What does string & number give?

never : aucune valeur ne peut être à la fois string et number, l'intersection est vide.never: no value can be both string and number, the intersection is empty.

TypeScriptUnionsIntersectionsSystème de typesModèle mental

← Tous les articlesAll articles