What it is and why to use it
JavaScript can throw any value, not just an Error instance. useUnknownInCatchVariables makes catch bindings unknown so code must check them before reading a message. It is enabled by strict unless explicitly overridden, and helps error handling reflect real runtime possibilities.
Common mistakes and limitations
An assertion error as Error does not verify what was thrown. instanceof Error is useful for local exceptions but realm boundaries can complicate identity. Keep raw diagnostic information separate from user-visible text.
Run this example
Use TypeScript 5.8 or later with strict checking and an ES2022 target. Save each complete example independently as example.ts, compile it, then run the generated JavaScript with a compatible Node.js installation. Compiler-only options below affect checking; they do not add runtime validation.
Terminal — compile and run
npx tsc example.ts --strict --target ES2022 --module commonjs
node example.jsSyntax
"useUnknownInCatchVariables": trueExamples
Safe catch Variables
Standalone TypeScript 5.8+ example; expected output is explained below.
function messageOf(value: unknown): string {
return value instanceof Error ? value.message : "Unknown failure";
}
try {
throw new Error("Could not load");
} catch (error) {
console.log(messageOf(error));
}
console.log(messageOf("raw failure"));- The Error instance provides a checked message property.
- The catch binding is passed to a helper that accepts unknown.
- A thrown string would use the fallback rather than being treated as an Error. In a public interface, choose a user-safe message rather than displaying sensitive internal details.
- Expected output: Could not load Unknown failure
Best practices
- An assertion error as Error does not verify what was thrown. instanceof Error is useful for local exceptions but realm boundaries can complicate identity. Keep raw diagnostic information separate from user-visible text.
- Keep external-input validation separate from compile-time type descriptions.
Runtime & versions
Compiled to JavaScript. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
TypeScript Handbook