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