The answer posted by rickstaa works, but it is not 100% safe. The code
property could be set to another type by a third party.
I would recommend to set in the declaration file (ie: @types/global.d.ts
) the following:
declare interface Error {
code?: unknown;
}
It is enough to access code
, check its value, and will rightfully require you to check its actual type before using it where a string or a number is needed.
No need to redeclare name
, message
and stack
, the declaration will merge with the one provided by TypeScript.
About the answer posted by Brent, I would strongly advise against casting the type like this:
.catch((reason: NodeJS.ErrnoException) => {
...
});
I think you shouldn't assume you know all reasons a Promise
could be rejected. In my opinion, you should always assume it is unknown
and check its type. There's a reason TypeScript types it a an any
. After declaring the code
property like demonstrated above, I would write this:
.catch((reason) => {
if (reason instanceof Error) {
// Here we can access reason.code
}
});
NodeJS
symbol. – Chaffee