Error Handling in Typescript
Exceptions caught in a try/catch
are not guaranteed to be an instance of Error
class, or a child of Error
. The exception caught can be anything - an object of any type, string, number, null... you name it.
So in typescript, the compiler won't like:
try {
//...
} catch(e) {
console.log(e.message); // => Compiler will error with `Object is of type 'unknown`
}
The typescript compiler can't infer the type of e
, so defaults the type to unknown
. If you know your error will have a message, you can do something like this:
try {
//...
} catch(e) {
const error = e as { message: string };
console.log(error.message);
}
Tweet