Recently delving into TypeScript, I decided to subclass Error and add a new method called getCode() in my MyError class.
export class MyError extends Error {
public code: number;
constructor(code: number, message?: string) {
super(message);
Error.captureStackTrace(this, MyError);
this.name = 'MyError';
this.code = code;
}
public getCode() {
return 405;
}
}
let errorInstance: MyError = new MyError(404, "test");
console.log(errorInstance.getCode());
In attempting to access the getCode() method of an instance of MyError class, I encountered the following error. It made me question whether custom methods can be added to subclasses, as I couldn't comprehend why the function getCode() was not being found.
console.log(errorInstance.getCode());
TypeError: errorInstance.getCode is not a function
at Object.<anonymous> (c:\Users\test\vscode-ws\MyError.js:35:15)
at Module._compile (internal/modules/cjs/loader.js:701:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:712:10)
at Module.load (internal/modules/cjs/loader.js:600:32)