TypeScript Classes and Modules/Narrow caught errors

Handle `unknown` errors in catch blocks safely.

Section: Errors and Validation Boundaries

Narrow caught errors

typescript
typescript
try {
  riskyWork();
} catch (error: unknown) {
  if (error instanceof Error) {
    console.error(error.message);
  }
}
Explanation

Catches should treat errors as unknown at boundaries and narrow deliberately.

Learn the surrounding workflow

Compare similar commands or jump into common fixes when this command is part of a bigger troubleshooting path.

Related commands

Same sheet · prioritizing Errors and Validation Boundaries
Parse JSON into `unknown` first
Treat external JSON as unsafe until validated.
OpenIn sheettypescriptsame section
Define a class
Type instance fields and constructor parameters.
OpenIn sheettypescript1 tag match
Named export
Export multiple values from a module.
OpenIn sheettypescript1 tag match
Use access modifiers
Control visibility with `public`, `private`, and `protected`.
OpenIn sheettypescript1 tag match
Default export
Export one primary value from a module.
OpenIn sheettypescript1 tag match
Readonly class fields
Prevent reassignment after construction.
OpenIn sheettypescript1 tag match