Lesson

TypeScript Error Handling

10 min reading
Free Course

TypeScript Error Handling: Narrowing unknown and Result Types

In JavaScript, throw can throw anything—an Error, a string, or even null. Because TypeScript cannot guarantee what a try block throws, strict mode types catch (err) as unknown, requiring you to narrow err before reading .message or .stack.

For predictable domain failures (like validation or "record not found"), returning a typed Result discriminated union makes error handling explicit in every function signature.

Safely Narrowing catch (err: unknown)

Always write a tiny helper to normalize unknown caught values cleanly:

class ValidationError extends Error {
  constructor(public readonly field: string, message: string) {
    super(message);
    this.name = "ValidationError";
  }
}

function getErrorMessage(err: unknown): string {
  if (err instanceof Error) return err.message;
  if (typeof err === "string") return err;
  return "Unknown error occurred";
}

try {
  throw new ValidationError("email", "Invalid email format");
} catch (err: unknown) {
  if (err instanceof ValidationError) {
    console.log(`Field ${err.field}: ${err.message}`);
  } else {
    console.log(getErrorMessage(err));
  }
}

Explicit Result<T, E> Pattern for Business Logic

Unlike throw (which TypeScript signatures do not track), a Result union forces callers to handle both success and failure branches:

type Result<T, E = string> =
  | { ok: true; value: T }
  | { ok: false; error: E };

function divide(a: number, b: number): Result<number> {
  if (b === 0) return { ok: false, error: "Cannot divide by zero" };
  return { ok: true, value: a / b };
}

const out = divide(10, 0);
console.log(out.ok ? out.value : out.error);

Common Mistakes to Avoid

  • Annotating catch (err: any) just to read err.message: If a library throws a string or plain object, err.message evaluates to undefined silently.
  • Forgetting this.name in custom Error subclasses: Setting this.name = "ValidationError" keeps stack traces and log filters readable.
  • Swallowing errors inside empty catch {} blocks: Always log, rethrow, or return a structured failure result.

Frequently Asked Questions

Does TypeScript support checked exceptions like Java's throws?

No. TypeScript function signatures only declare return types, which is why Result<T, E> unions are popular for recoverable domain errors.

Why is err instanceof Error sometimes tricky across iframes or Node realms?

Objects created in another VM realm have a different Error constructor; check "message" in err or Error.isError(err) in modern runtimes when crossing realms.

When should I throw vs return a Result object?

Throw exceptions for unexpected bugs, programmer errors, or top-level framework boundaries (HTTP handlers). Return Result unions for expected validation or business-rule outcomes.

Save Your Progress

Unlock Your
Full Potential.

Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.

Quick Access With

Enterprise-Grade Security Protocol

Try it Yourself

Experiment with the code from this lesson in our interactive playground.

Open Playground
TypeScript Topic Hub

Stuck on this lesson?

Join our community of senior developers.

Ask in Forum