Issue
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?
Solution
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
catchclause variables asunknowninstead.unknownis safer thananybecause 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})`,
};
}
}
Answered By - Jason Owen
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.