How can I safely access caught Error properties in TypeScript?

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})`,
    };
  }
}

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)