En bref. On cherche d’où viennent les any de son code, et on les cherche au mauvais endroit : presque tous entrent par la porte.
Le modèle en une phrase
Les any entrent par la frontière, là où des données extérieures franchissent le programme : c’est là qu’il faut exiger la preuve.
In short. You look for where your code’s anys come from, and you look in the wrong place: almost all of them come in through the door.
The model in one sentence
anys enter at the boundary, where external data crosses into the program: that’s where to demand proof.
const viaParse = JSON.parse(…) // anyconst n: number = viaParse // et string aussiconst h: unknown = JSON.parse(…)
const viaParse = JSON.parse(…) // any— JSON.parse ne peut rien savoir d'une chaîne : il renvoie any, et le trou entre dans le programme.JSON.parse can know nothing about a string: it returns any, and the hole enters the program.const n: number = viaParse // et string aussi— any est assignable à number comme à string : deux types incompatibles acceptent la même valeur, qui est un objet.any is assignable to number as well as string: two incompatible types accept the same value, which is an object.const h: unknown = JSON.parse(…)— En déclarant unknown à la frontière, tsc réclame la preuve avant tout usage : le trou est refermé à l'entrée.By declaring unknown at the boundary, tsc demands proof before any use: the hole is closed at the entrance.
La preuve, avec du code qui tourne
JSON.parse, une réponse réseau, un catch : trois entrées, une même brèche :
// Les any n'arrivent presque jamais par notre faute : ils entrent par la frontière.
const viaParse = JSON.parse('{"nom":"Ada"}'); // any
const viaFetch = await new Response('{"nom":"Ada"}').json(); // any aussi
// any est assignable à tout : deux types incompatibles acceptent la même valeur.
const n: number = viaParse;
const s: string = viaFetch;
console.log(typeof n, typeof s); // object object : les types ont menti
// Une frontière honnête : on déclare unknown, tsc réclame la preuve.
const honnete: unknown = JSON.parse('{"nom":"Ada"}');
// @ts-expect-error unknown n'est pas assignable à number
const m: number = honnete;
// Même le catch est une frontière : strict le type unknown.
try { throw new Error("boom"); }
catch (e) {
// @ts-expect-error e est unknown : message n'est pas garanti
console.log(e.message);
}
export {};object object
boomLe fichier compile en strict avec tsc 6. JSON.parse et la lecture JSON d’une réponse renvoient any, assignable à number comme à string : à l’exécution, les deux valent un objet. Déclarer unknown refuse l’affectation à number, ts-expect-error le prouve. Le catch en strict type aussi l’erreur unknown, ce qui refuse l’accès direct à message.
Ce que l’image cache
Le problème n’est pas any lui-même, mais l’endroit où il naît : une frontière non gardée contamine tout le code en aval. Poser un unknown à chaque entrée, puis valider, est plus efficace que chasser les any un par un après coup.
Pour aller plus loin
Le numéro ci-dessous détaille les frontières qui produisent des any, comment les reconnaître, et pourquoi la validation s’y place.
The proof, with running code
JSON.parse, a network response, a catch: three entrances, one same breach:
// anys almost never arrive through our fault: they enter at the boundary.
const viaParse = JSON.parse('{"nom":"Ada"}'); // any
const viaFetch = await new Response('{"nom":"Ada"}').json(); // any too
// any is assignable to everything: two incompatible types accept the same value.
const n: number = viaParse;
const s: string = viaFetch;
console.log(typeof n, typeof s); // object object: the types lied
// An honest boundary: we declare unknown, tsc demands proof.
const honnete: unknown = JSON.parse('{"nom":"Ada"}');
// @ts-expect-error unknown n'est pas assignable à number
const m: number = honnete;
// Even catch is a boundary: strict types it as unknown.
try { throw new Error("boom"); }
catch (e) {
// @ts-expect-error e est unknown : message n'est pas garanti
console.log(e.message);
}
export {};object object
boomThe file compiles in strict mode with tsc 6. JSON.parse and the JSON reading of a response return any, assignable to number as well as string: at runtime, both are an object. Declaring unknown refuses assignment to number, ts-expect-error proves it. In strict mode catch also types the error as unknown, which refuses direct access to message.
What the picture hides
The problem isn’t any itself, but where it is born: an unguarded boundary contaminates all the downstream code. Putting an unknown at every entrance, then validating, is more effective than hunting anys one by one afterwards.
Go deeper
The issue below details the boundaries that produce anys, how to recognize them, and why validation belongs there.