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 …
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.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.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.
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 : TypeErrorLe 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 : TypeErrorThe 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.