Error Handling with unknown

catch Gives unknown

In strict mode (useUnknownInCatchVariables), the variable in catch (e) is unknown, because JavaScript lets you throw anything: strings, numbers, objects. Check before using it.

Example

Reading e.message directly is TS18046.

try {
  JSON.parse("{bad json");
} catch (e) {
  console.log(e.message);
}

Compiler output (tsc)

Line 4: error TS18046: 'e' is of type 'unknown'.

A Safe Error Message Helper

Example

function errorMessage(e: unknown): string {
  if (e instanceof Error) return e.message;
  if (typeof e === "string") return e;
  return "Unknown error: " + JSON.stringify(e);
}

async function risky(kind: number): Promise<string> {
  if (kind === 1) throw new Error("Payment gateway timeout");
  if (kind === 2) throw "plain string thrown";
  if (kind === 3) throw { code: 500 };
  return "success";
}

async function main() {
  for (const kind of [0, 1, 2, 3]) {
    try {
      console.log(await risky(kind));
    } catch (e) {
      console.log("Caught:", errorMessage(e));
    }
  }
}
main();

Output

success
Caught: Payment gateway timeout
Caught: plain string thrown
Caught: Unknown error: {"code":500}

Tip: Always await (or return) promises inside try. A promise that is not awaited rejects later, outside the try, and becomes an unhandled rejection.