Le narrowing : le modèle mental de la preuve construite branche par branche en TypeScript Narrowing: the mental model of the proof built branch by branch in TypeScript

TypeScript ne convertit pas une valeur : il la prouve. À chaque if, typeof ou retour anticipé, l'union perd un membre, jusqu'à savoir exactement ce qu'on tient.TypeScript doesn't cast a value: it proves it. At each if, typeof or early return, the union loses a member, until it knows exactly what you hold.

AuteurAuthor
Ludovic Cleuet
ThèmeTopic
EffacementType erasure
PubliéPublished

En bref. Un paramètre string ou number ou null, et pourtant on appelle une méthode de string sans erreur. Qui a prouvé quoi ?

Le modèle en une phrase

TypeScript ne convertit pas la valeur : il la prouve, branche par branche, en retirant un membre de l’union à chaque test.

In short. A parameter that is string or number or null, yet we call a string method without error. Who proved what?

The model in one sentence

TypeScript doesn’t convert the value: it proves it, branch by branch, removing one member of the union at each test.

function decrire(x: string | number | null)
if (x === null) return "rien"
if (typeof x === "string") return …
La preuve, branche par brancheThe proof, branch by branchtrois possibilitéstrois possibilitésstringnumbernull3 membre(s) possible(s)3 possible member(s)exemple exécuté avec bun et vérifié par tscexample run with bun and checked by tsc
  1. function decrire(x: string | number | null) — Au départ, x peut être string, number ou null : rien n'est permis sans preuve.At the start, x can be string, number or null: nothing is allowed without proof.
  2. if (x === null) return "rien" — Après le retour anticipé, null est éliminé : x est string ou number.After the early return, null is eliminated: x is string or number.
  3. if (typeof x === "string") return … — Après le test typeof, string est éliminé aussi : x est number. Le type est prouvé branche par branche.After the typeof test, string is eliminated too: x is number. The type is proven branch by branch.
TypeScript ne convertit pas x : il le prouve. À chaque if, chaque typeof, chaque retour anticipé, l'union perd un membre, jusqu'à savoir exactement ce qu'on tient.TypeScript doesn't cast x: it proves it. At each if, each typeof, each early return, the union loses a member, until it knows exactly what you hold.

La preuve, avec du code qui tourne

Une union de trois types, trois tests, et un appel sans preuve :

function decrire(x: string | number | null): string {
  if (x === null) return "rien";                // x : null
  if (typeof x === "string") return x.toUpperCase();   // x : string
  return x.toFixed(2);                          // x : number (il ne reste que lui)
}

console.log(decrire(null));
console.log(decrire("ada"));
console.log(decrire(3.14159));

// À chaque branche, l'union perd un membre. Sans preuve, rien n'est permis :
function mal(x: string | number | null) {
  // @ts-expect-error  x peut être number ou null : toUpperCase n'est pas garanti
  return x.toUpperCase();
}
try { mal(42 as never); } catch (e) { console.log("sans narrowing :", (e as Error).constructor.name); }
rien
ADA
3.14
sans narrowing : TypeError

Le fichier compile en strict avec tsc 6. Après le test sur null, puis le test typeof, il ne reste que number : toFixed est permis. Sans ces tests, appeler toUpperCase est une erreur de compilation, que ts-expect-error prouve en la capturant. L’analyse suit le flot du code, pas des étiquettes que l’on colle.

Ce que l’image cache

Le narrowing ne vit qu’à la compilation : à l’exécution, ce sont de vrais tests (typeof, comparaisons) qui s’exécutent, et ils restent corrects seulement si on les écrit. Il s’invalide aussi : une affectation, un rappel de fonction ou une mutation peuvent faire oublier ce qui était prouvé.

Pour aller plus loin

Le numéro ci-dessous détaille les formes de narrowing (typeof, in, égalité, truthiness), l’analyse de flot et ses limites.

The proof, with running code

A union of three types, three tests, and a call without proof:

function decrire(x: string | number | null): string {
  if (x === null) return "rien";                // x: null
  if (typeof x === "string") return x.toUpperCase();   // x: string
  return x.toFixed(2);                          // x: number (the only one left)
}

console.log(decrire(null));
console.log(decrire("ada"));
console.log(decrire(3.14159));

// At each branch, the union loses a member. Without proof, nothing is allowed:
function mal(x: string | number | null) {
  // @ts-expect-error  x peut être number ou null : toUpperCase n'est pas garanti
  return x.toUpperCase();
}
try { mal(42 as never); } catch (e) { console.log("sans narrowing :", (e as Error).constructor.name); }
rien
ADA
3.14
sans narrowing : TypeError

The file compiles in strict mode with tsc 6. After the null test, then the typeof test, only number remains: toFixed is allowed. Without those tests, calling toUpperCase is a compile error, which ts-expect-error proves by catching it. The analysis follows the flow of the code, not labels you stick on.

What the picture hides

Narrowing only lives at compile time: at runtime, real tests (typeof, comparisons) run, and they are only correct if you write them. It can also be invalidated: an assignment, a callback or a mutation can make the compiler forget what was proven.

Go deeper

The issue below details the forms of narrowing (typeof, in, equality, truthiness), flow analysis and its limits.

Questions fréquentesFrequently asked questions

Qu'est-ce que le narrowing ?What is narrowing?

Le raffinement d'un type large vers un type plus précis, grâce à des tests que le compilateur comprend : typeof, égalité, in, instanceof, truthiness.Refining a wide type into a more precise one, thanks to tests the compiler understands: typeof, equality, in, instanceof, truthiness.

Qu'est-ce que l'analyse de flot ?What is flow analysis?

Le compilateur suit le chemin du code : après un retour anticipé ou un if, il sait quels membres de l'union restent possibles.The compiler follows the path of the code: after an early return or an if, it knows which members of the union remain possible.

Pourquoi toUpperCase est-il refusé sans test ?Why is toUpperCase rejected without a test?

Parce que la valeur peut être un number ou null, qui n'ont pas cette méthode. Sans preuve, l'appel n'est pas garanti.Because the value may be a number or null, which don't have that method. Without proof, the call is not guaranteed.

Le narrowing change-t-il la valeur ?Does narrowing change the value?

Non. Il ne change que ce que le compilateur sait d'elle. À l'exécution, seuls les vrais tests s'exécutent.No. It only changes what the compiler knows about it. At runtime, only the real tests run.

Quand le narrowing se perd-il ?When is narrowing lost?

Après une affectation, dans un rappel de fonction, ou quand l'objet peut être muté : le compilateur ne peut plus garantir ce qui était prouvé.After an assignment, inside a callback, or when the object can be mutated: the compiler can no longer guarantee what was proven.

TypeScriptNarrowingAnalyse de flotUnionsModèle mental

← Tous les articlesAll articles