LearnThatStack Ace your next interview
TypeScript · question
Question 13 of 102

How do you handle errors in TypeScript?

beginner
← All TypeScript questions
Re-explain

You handle errors with JavaScript's try and catch. Under strict, TypeScript types the caught value as unknown, because JavaScript can throw anything, not only Error objects. You narrow it before you use it.

function parseNumber(value: string): number {
  try {
    const parsed = parseInt(value);
    if (isNaN(parsed)) {
      throw new Error(`Invalid number: ${value}`);
    }
    return parsed;
  } catch (error) {
    if (error instanceof Error) {
      console.error(error.message);
    }
    throw error;
  }
}
// Custom error types
class ValidationError extends Error {
  constructor(
    message: string,
    public field: string,
    public value: any
  ) {
    super(message);
    this.name = 'ValidationError';
  }
}

The instanceof Error check narrows error, so error.message compiles. The useUnknownInCatchVariables option, part of strict, sets that default. Without it the variable is any, and the compiler checks nothing.

Custom error classes extend Error and add typed fields, like field and value on ValidationError. Setting name makes logs show which error it was. A caller can test err instanceof ValidationError and then read err.field safely.

TypeScript does not track which errors a function throws, so document them, or return a result type for failures callers must handle.

Rewriting in plainer words…

This answer doesn't lend itself to a diagram - it reads best . No credits were charged.

Why there's no diagram: “”

The interactive diagram is below the answer - jump to diagram ↓ · Below it, the related concept . Jump to it ↓

The diagram below the answer is the concept . Jump to it ↓

Tailored explanation · switch back to · ·
What should the new diagram focus on?
How well did you know this?
AI:

Saved in this browser - sign in to keep your review list.

How should your speech become text?

Listening… your words appear above as you speak - tap Stop when you're done.

Recording · cr - tap Stop & transcribe when you're done.

Transcribing with AI…

Voice:

Keep going - a few more words and AI can grade it.

Interview lens

Likely follow-ups, what you can say, and the weak answers to avoid.

Sign in free to open it Free account - the lens opens as soon as you're back.

Want a quick review of the fundamentals? See the TypeScript cheatsheet.

← Back to all TypeScript questions
Pro · $10/mo

86 of 102 TypeScript answers are in Pro.

Full answers, code samples, and AI explanations that go simpler or deeper. Cancel anytime.

  • Full answers + code
  • AI explanations, simpler or deeper
  • 1,000 AI credits / month
  • Cancel anytime