Error typing (unknown), narrowing in catch
Type catch parameters as unknown, then narrow with instanceof/typeof or custom guards for safe error handling.
Intro
Goal: Catch errors as unknown and narrow safely. You will use instanceof, typeof, and custom type guards to read error data without surprises.
unknown + instanceof
Start with unknown. Narrow with instanceof Error to access message, stack, etc.
async function boom(): Promise<void> { throw new Error("boom") }
async function run() {
try {
await boom();
} catch (e: unknown) {
if (e instanceof Error) {
console.error("Handled:", e.message);
} else {
console.error("Non-Error thrown:", e);
}
}
}
run();All lessons in this course
- Promise , async/await typing
- Error typing (unknown), narrowing in catch
- Concurrency patterns (all/settled/race) types