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.
try {
throw new Error('foo');
} catch (err: Error) {
const { message }: { message: string } = err;
return {
message: `Things exploded (${message})`,
};
}
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
).
How can I catch an error in TypeScript and access the Error's properties?
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) {} .
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.
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.
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 asunknown
instead.unknown
is safer thanany
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})`,
};
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With