Today I Learned

hashrocket A Hashrocket project

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);
}
See More #javascript TILs
Looking for help? At Hashrocket, our JavaScript experts launch scalable, performant apps on the Web, Android and iOS. Contact us and find out how we can help you.