[FIXED] Property 'code' does not exist on type 'Error'

Issue

How can I access the Error.code property?
I get a Typescript error because the property ‘code’ does not exist on type ‘Error’.

this.authCtrl.login(user, {
   provider: AuthProviders.Password,
   method: AuthMethods.Password
}).then((authData) => {
    //Success
}).catch((error) => {
   console.log(error); // I see a code property
   console.log(error.code); //error
})

Solution

The real issue is that the Node.js definition file isn’t exporting a proper Error definition. It uses the following for Error (and doesn’t export this):

interface Error {
    stack?: string;
}

The actual definition it exports is in the NodeJS namespace:

export interface ErrnoException extends Error {
    errno?: number;
    code?: string;
    path?: string;
    syscall?: string;
    stack?: string;
}

So the following typecast will work:

.catch((error: NodeJS.ErrnoException) => {
    console.log(error);
    console.log(error.code);
})

This seems like a flaw in Node’s definition, since it doesn’t line up with what an object from new Error() actually contains. TypeScript will enforce the interface Error definition.

Answered By – Brent

Answer Checked By – Katrina (FixeMe Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *