WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

TypeScript · Guru · question 93 of 100

How can you leverage TypeScript’s type system for better error handling and failure recovery at runtime?

📕 Buy this interview preparation book: 100 TypeScript questions & answers — PDF + EPUB for $5

Typescript’s type system strongly focuses on providing static type checking and catching errors during development to ensure code correctness before runtime. While it doesn’t directly offer runtime error handling and recovery mechanisms, there are still various ways you can leverage Typescript features to write better error handling and recovery solutions.

1. Advanced types for function inputs and outputs:

You can create more specific types to enforce your functions’ inputs and outputs, which can lead to better self-documenting code and make error handling more straightforward.

For example, imagine you have a function that takes an input and returns a ‘Result‘ type that contains an error message, if any:

type Result<T> = { success: true; data: T } | { success: false; error: string };

function myFunction(input: number): Result<number> {
  if (input < 0) {
    return { success: false, error: "Negative number not allowed" };
  }

  // Do some processing
  const result = input * 2;

  return { success: true, data: result };
}

const result = myFunction(-5);
if (!result.success) {
  console.error(result.error);
} else {
  console.log(result.data);
}

By using the ‘Result‘ type, you express the possible failure explicitly and force yourself and other developers to handle it during runtime.

2. Custom error classes:

You can create custom error classes that provide additional context about the error and make it easier to handle particular error scenarios:

class MyError extends Error {
  constructor(public code: number, message?: string) {
    super(message);
  }
}

Then in your functions, you can throw or catch these custom errors and handle them according to the error codes:

function throwError(): never {
  throw new MyError(404, "Not found");
}

try {
  throwError();
} catch (error) {
  if (error instanceof MyError) {
    console.error(`Error with code ${error.code}: ${error.message}`);
  } else {
    console.error(`Unknown error: ${error.message}`);
  }
}

3. Type guards and discriminated unions:

If you’re dealing with different kinds of errors and their handling, you can write discriminated unions for these errors and use type guards to enforce a specific handling process based on their type.

type APIError = { type: "APIError"; statusCode: number; message: string };
type ValidationError = { type: "ValidationError"; errors: string[] };

type AppError = APIError | ValidationError;

function handleAppError(error: AppError) {
  if (isAPIError(error)) {
    // Handle APIError
    console.error(`API Error: Status - ${error.statusCode}, Message - ${error.message}`);
  } else {
    // Handle ValidationError
    console.error(`Validation Errors: ${error.errors.join(", ")}`);
  }
}

function isAPIError(error: AppError): error is APIError {
  return error.type === "APIError";
}

const apiError: APIError = {
  type: "APIError",
  statusCode: 404,
  message: "Not Found",
};

const validationError: ValidationError = {
  type: "ValidationError",
  errors: ["Name is required", "Email is invalid"],
};

handleAppError(apiError);
handleAppError(validationError);

Here, the ‘AppError‘ type is a union of ‘APIError‘ and ‘ValidationError‘. The custom type guard ‘isAPIError‘ helps in identifying the error type and handling it accordingly.

While TypeScript can’t catch all runtime errors, the features mentioned above can help you build better error handling mechanisms in your TypeScript projects. Although TypeScript doesn’t modify the runtime behavior of JavaScript, these techniques ensure that you and your teammates consider error cases resulting in more robust code.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic TypeScript interview — then scores it.
📞 Practice TypeScript — free 15 min
📕 Buy this interview preparation book: 100 TypeScript questions & answers — PDF + EPUB for $5

All 100 TypeScript questions · All topics