Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I safely access caught Error properties in TypeScript?

Tags:

typescript

The Situation

I am using TypeScript, and have a try / catch block. The caught error is typed (Error). I would like to use the error's message attribute.

I am using eslint with the @typescript-eslint/no-unsafe-assignment rule enabled.

The Code

try {
  throw new Error('foo');
} catch (err: Error) {
  const { message }: { message: string } = err;
  return {
    message: `Things exploded (${message})`,
  };
}

The Problem

When I run my linter, I receive the following:

  4:9  error  Unsafe assignment of an any value  @typescript-eslint/no-unsafe-assignment

This is confusing to me, since the error is typed (Error).

The Question

How can I catch an error in TypeScript and access the Error's properties?

like image 270
slifty Avatar asked Oct 20 '20 19:10

slifty


People also ask

How do you handle unknown error TypeScript?

The "Object is of type unknown" error occurs when we try to access a property on a value that has a type of unknown . To solve the error, use a type guard to narrow down the type of the object before accessing a property, e.g. if (err instanceof Error) {} .

How do you use try catch in TypeScript?

The try catch in TypeScript statement provides a way to handle some or all of the errors that may occur in an application. These errors are often referred to as an exception. In a try-catch statement, you code a try block that contains the statements that may throw an exception.

How do you throw a TypeScript error?

To declare a function that throws an error, set its return type to never . The never type is used for functions that never return a value, in other words functions that throw an exception or terminate execution of the program.


1 Answers

TypeScript 4.0 introduced the ability to declare the type of a catch clause variable... so long as you type it as unknown:

TypeScript 4.0 now lets you specify the type of catch clause variables as unknown instead. unknown is safer than any because it reminds us that we need to perform some sorts of type-checks before operating on our values.

We don't have the ability to give caught errors arbitrary types; we still need to use type guards to examine the caught value at runtime:

try {
  throw new Error('foo');
} catch (err: unknown) {
  if (err instanceof Error) {
    return {
      message: `Things exploded (${err.message})`,
    };
  }
}
like image 100
Jason Owen Avatar answered Oct 03 '22 08:10

Jason Owen