Erreur non typée : le modèle mental de ce qu'on peut lancer n'importe quoi en TypeScript Untyped errors: the mental model of being able to throw anything in TypeScript

En JavaScript, throw accepte n'importe quelle valeur : le catch reçoit unknown. On ne lit l'erreur qu'après l'avoir vérifiée, et le type d'une Promise ne dit rien de son rejet.In JavaScript, throw accepts any value: catch receives unknown. You only read the error after checking it, and a Promise's type says nothing about its rejection.

AuteurAuthor
Ludovic Cleuet
ThèmeTopic
AsyncAsync
PubliéPublished

En bref. Une fonction peut lancer, mais sa signature ne dit pas quoi. En TypeScript, l’erreur attrapée est inconnue.

Le modèle en une phrase

On peut lancer n’importe quoi, donc le catch reçoit unknown : on ne lit l’erreur qu’après l’avoir vérifiée.

In short. A function can throw, but its signature doesn’t say what. In TypeScript, the caught error is unknown.

The model in one sentence

You can throw anything, so catch receives unknown: you only read the error after checking it.

throw new Error("boum") / throw "texte" / throw { code: 42 }
catch (e) { e.message } // e : unknown
if (e instanceof Error) return e.message
L'erreur n'est pas typéeThe error is not typedon peut lancer n'importe quoion peut lancer n'importe quoithrowError, string, objetcatchtout est lançablelecture refusée : type inconnureading refused: unknown typeexemple exécuté avec bun et vérifié par tscexample run with bun and checked by tsc
  1. throw new Error("boum") / throw "texte" / throw { code: 42 } — En JavaScript, throw accepte n'importe quelle valeur : une Error, un texte, un objet. Rien ne l'impose.In JavaScript, throw accepts any value: an Error, a string, an object. Nothing enforces otherwise.
  2. catch (e) { e.message } // e : unknown — Le catch reçoit donc unknown : lire e.message est refusé, car ce n'est pas forcément une Error.So catch receives unknown: reading e.message is refused, because it isn't necessarily an Error.
  3. if (e instanceof Error) return e.message — Un test (instanceof, typeof) restreint le type : à l'intérieur, on peut enfin lire l'erreur sans mentir.A check (instanceof, typeof) narrows the type: inside it, you can finally read the error without lying.
En JavaScript on peut lancer n'importe quoi, donc le catch reçoit unknown : on ne lit l'erreur qu'après l'avoir vérifiée. Le type de la valeur de retour ne dit rien de ce qui peut être lancé.In JavaScript you can throw anything, so catch receives unknown: you only read the error after checking it. A function's return type says nothing about what it may throw.

La preuve, avec du code qui tourne

Lancer trois types de valeurs, les attraper, puis un rejet de promesse :

// En JavaScript, on peut lancer n'importe quoi : pas seulement une Error.
function lancer(quoi: unknown): never { throw quoi; }

function attraper(quoi: unknown): string {
  try {
    lancer(quoi);
  } catch (e) {
    // En strict, e est unknown : on ne peut pas lire e.message sans vérifier.
    // @ts-expect-error  'e' est de type 'unknown'
    const trop_tot = e.message;
    if (e instanceof Error) return "Error : " + e.message;
    if (typeof e === "string") return "string : " + e;
    return "autre : " + JSON.stringify(e);
  }
  return "rien";
}

console.log(attraper(new Error("boum")));
console.log(attraper("texte lancé"));
console.log(attraper({ code: 42 }));

// Le type d'une promesse ne dit rien de son erreur : le rejet n'est pas typé.
const echec: Promise<number> = Promise.reject(new TypeError("refusé"));
try { await echec; } catch (e) {
  console.log("rejet reconnu :", e instanceof TypeError);
}
export {};
Error : boum
string : texte lancé
autre : {"code":42}
rejet reconnu : true

Le fichier compile en strict avec tsc 6. Dans le catch, e est unknown : lire e.message est refusé, ts-expect-error le prouve. Après instanceof Error ou typeof, on peut lire. Les trois cas lancés (Error, texte, objet) sont bien attrapés, et le rejet d’une promesse se reconnaît de la même façon.

Ce que l’image cache

Ce modèle ne dit pas qui peut lancer quoi : rien dans la signature d’une fonction n’indique qu’elle peut échouer ni avec quelle erreur. Les erreurs venues de bibliothèques ou du réseau sont souvent des objets sans classe commune, et un instanceof peut échouer entre deux contextes d’exécution.

Pour aller plus loin

Le numéro ci-dessous détaille la restriction de l’erreur, les erreurs comme valeurs, et le rejet des promesses.

The proof, with running code

Throwing three kinds of values, catching them, then a promise rejection:

// In JavaScript, you can throw anything: not only an Error.
function lancer(quoi: unknown): never { throw quoi; }

function attraper(quoi: unknown): string {
  try {
    lancer(quoi);
  } catch (e) {
    // In strict mode, e is unknown: you can't read e.message without checking.
    // @ts-expect-error  'e' est de type 'unknown'
    const trop_tot = e.message;
    if (e instanceof Error) return "Error : " + e.message;
    if (typeof e === "string") return "string : " + e;
    return "autre : " + JSON.stringify(e);
  }
  return "nothing";
}

console.log(attraper(new Error("boum")));
console.log(attraper("thrown text"));
console.log(attraper({ code: 42 }));

// A promise's type says nothing about its error: the rejection is not typed.
const echec: Promise<number> = Promise.reject(new TypeError("refused"));
try { await echec; } catch (e) {
  console.log("rejection recognised:", e instanceof TypeError);
}
export {};
Error : boum
string : texte lancé
autre : {"code":42}
rejet reconnu : true

The file compiles in strict mode with tsc 6. In the catch, e is unknown: reading e.message is refused, ts-expect-error proves it. After instanceof Error or typeof, you can read. The three thrown cases (Error, string, object) are all caught, and a promise rejection is recognised the same way.

What the picture hides

This model doesn’t say who can throw what: nothing in a function’s signature indicates it can fail or with which error. Errors from libraries or the network are often objects with no common class, and an instanceof can fail across two execution contexts.

Go deeper

The issue below details narrowing the error, errors as values, and promise rejection.

Questions fréquentesFrequently asked questions

Quel est le type de l'erreur dans un catch ?What is the type of the error in a catch?

unknown en strict (useUnknownInCatchVariables) : on peut lancer n'importe quelle valeur, donc il faut la vérifier avant de la lire.unknown in strict mode (useUnknownInCatchVariables): you can throw any value, so you must check it before reading it.

Peut-on lancer autre chose qu'une Error ?Can you throw something other than an Error?

Oui. throw accepte un texte, un nombre ou un objet : rien ne l'impose, mais c'est déconseillé.Yes. throw accepts a string, a number or an object: nothing prevents it, though it is discouraged.

Comment lire l'erreur proprement ?How do you read the error safely?

Avec un test : instanceof Error pour les erreurs classiques, typeof pour un texte. Après le test, le type est restreint.With a check: instanceof Error for classic errors, typeof for a string. After the check, the type is narrowed.

Une fonction peut-elle déclarer ce qu'elle lance ?Can a function declare what it throws?

Non. La signature décrit le retour, pas les erreurs : TypeScript n'a pas d'équivalent des exceptions vérifiées.No. The signature describes the return, not errors: TypeScript has no equivalent of checked exceptions.

Le rejet d'une Promise est-il typé ?Is a Promise rejection typed?

Non. Promise<number> décrit le succès seulement : le rejet arrive dans un catch en unknown.No. Promise<number> describes success only: the rejection arrives in a catch as unknown.

TypeScriptErreurscatchunknownModèle mental

← Tous les articlesAll articles