TypeScript方法装饰器报错:TypeError: 'instanceof'右侧不是对象
解决TypeScript方法装饰器中
instanceof报错的问题 你遇到的TypeError: Right-hand side of 'instanceof' is not an object错误,根源在于装饰器的执行时机和target参数的含义,下面一步步拆解:
报错原因
- 装饰器执行时机早于类初始化:当
@log装饰器运行时,Someone类还没完成定义,此时变量Someone的值是undefined。你写的target instanceof Someone相当于让一个对象和undefined做instanceof判断,自然触发报错——instanceof的右侧必须是合法的构造函数(对象类型)。 - 方法装饰器的
target不是实例:对于实例方法(比如hello),装饰器的第一个参数target是类的原型对象(也就是Someone.prototype),而不是类的实例或构造函数本身。
解决方案
方案1:正确识别target的类型
如果只是想验证target的身份,可以打印它的构造函数名称,不需要依赖未初始化的类变量:
export function log( target: any, propertyKey: string, descriptor: PropertyDescriptor ) { // 打印target的构造函数名称,输出"Someone" console.log(`target belongs to class:`, target.constructor.name); }
方案2:在方法运行时检查实例类型
如果需要判断实例是否属于Someone,可以在装饰器里重写原方法,等到方法被调用时(此时类已完全初始化),通过this(实例对象)做instanceof检查:
export function log( target: any, propertyKey: string, descriptor: PropertyDescriptor ) { const originalHello = descriptor.value; // 重写原方法,保留原有逻辑 descriptor.value = function(...args: any[]) { // 这里的this是类的实例,此时Someone已经定义完成 console.log(`this instanceof Someone ->`, this instanceof Someone); return originalHello.apply(this, args); }; return descriptor; } class Someone { constructor(public name: string) {} @log hello() { console.log(`Hello! My name is ${this.name}`); } } const inst = new Someone("Riksan"); inst.hello(); // 输出结果: // this instanceof Someone -> true // Hello! My name is Riksan
内容的提问来源于stack exchange,提问作者Hairi
相关产品推荐
相关产品推荐

