Handling unknown Errors
Handling unknown Errors — the core idea
JavaScript can throw any value: an Error object, a string, or another value. Under strict TypeScript, catch bindings are unknown. Narrow before reading message; for application boundaries, normalize unfamiliar values into a safe diagnostic.
What you’ll learn
- Explain handling unknown errors with a concrete use case.
- Run the example and account for every line of its output.
- Recognize the difference between compile-time checking and runtime behavior.
Understand the rules and when to use them
Reading the code: The instanceof check permits safe access to Error.message. The string is handled by String(error), so the second call prints offline without unsafe property access.
Keep the boundary clear: Avoid writing (error as Error).message without checking: a string or null may have no message property.
See the idea as a flow
Run the complete TypeScript example
Save the code as handling-unknown-errors.ts. The result below was captured after compiling this exact example with strict TypeScript checking and executing the emitted JavaScript in Node.js.
TypeScript code
function messageFrom(error: unknown): string {
return error instanceof Error ? error.message : String(error);
}
console.log(messageFrom(new Error("disk full")));
console.log(messageFrom("offline"));Verified output
disk full
offlineBuild: npx tsc --strict --target es2022 --module commonjs --lib es2022,dom,esnext.disposable handling-unknown-errors.ts; run: node handling-unknown-errors.js. The exact filename may be changed freely. When a multi-file project exists, prefer its tsconfig.json and build scripts.
Trace the example line by line
The instanceof check permits safe access to Error.message. The string is handled by String(error), so the second call prints offline without unsafe property access.
The output shown above comes from the initialized values in this program. Replacing a type annotation alone does not transform a JavaScript value.
Avoid this common mistake
Avoid writing (error as Error).message without checking: a string or null may have no message property.
Check both the TypeScript diagnostic and the emitted JavaScript behavior. A program can compile correctly and still need runtime validation or error handling.
Practice independently
Handle an object with a numeric code property without assuming every unknown thrown value has that shape.
Before running your change, write down the type you expect TypeScript to infer and the output you expect JavaScript to print. Then check both predictions.
Check your understanding
What to remember
JavaScript can throw any value: an Error object, a string, or another value.
Try the practice change and re-run the exact program to test your understanding.
Reaching the recap and completing the quizzes are separate milestones.