TypeScript类方法调用报错:TypeError: error.sendResponse is not a function
解决TypeError: error.sendResponse is not a function问题
问题原因
自定义类继承Error时,JavaScript的特殊机制会导致子类实例的原型链未正确关联到自定义类的原型上,进而让类中定义的sendResponse方法无法被实例访问。这是因为Error构造函数执行时会返回一个独立对象,覆盖了子类原本的this指向。
修复方案
在子类构造函数调用super()之后,手动修正原型链即可:
class AppError extends Error { statusCode: number; message: string; stacktrace?: any; constructor(statusCode: number, message: string, stacktrace?: any) { super(message); this.statusCode = statusCode; this.stacktrace = stacktrace; // 修复原型链,确保自定义方法能被实例调用 Object.setPrototypeOf(this, AppError.prototype); } sendResponse() { console.log('This function is called'); } } const error = new AppError(400, 'not found'); error.sendResponse(); // 现在能正常执行,输出"This function is called"
其他可选修复方式
也可以在类定义后显式设置原型链,效果和上面一致:
class AppError extends Error { // ... 其他代码保持不变 } // 手动关联原型链 AppError.prototype = Object.create(Error.prototype); AppError.prototype.constructor = AppError;
内容的提问来源于stack exchange,提问作者Naighu
相关产品推荐
相关产品推荐

