TypeScript装饰器报错:无法解析属性装饰器签名(ts1240)
解决TypeScript方法装饰器的类型错误问题
问题根源
你遇到的两个错误核心原因如下:
- 装饰器的签名是方法装饰器的标准格式,但你可能将其用在了非方法位置(比如类属性),导致TypeScript无法识别其签名。
- TypeScript对不同类型装饰器的返回值有明确要求:方法装饰器可以返回
PropertyDescriptor,但属性装饰器只能返回void或any,类型不匹配就会触发报错。
修正步骤
1. 确保tsconfig.json配置正确
首先检查你的tsconfig.json,必须开启装饰器相关编译选项:
{ "compilerOptions": { "target": "ES5", "experimentalDecorators": true, "emitDecoratorMetadata": true // 可选,用于获取元数据 } }
2. 修正装饰器实现(添加计时逻辑+正确类型)
你的当前装饰器仅返回原descriptor,未实现计时功能,同时可以优化类型定义,避免强制any转换:
// 创建用于记录方法执行时间的装饰器 export function logExecutionTime() { return function ( target: Object, propertyKey: string | symbol, descriptor: PropertyDescriptor ): PropertyDescriptor { // 保存原方法引用 const originalMethod = descriptor.value; // 重写方法,注入计时逻辑 descriptor.value = function (...args: any[]) { const start = performance.now(); const result = originalMethod.apply(this, args); const end = performance.now(); console.log(`方法 ${String(propertyKey)} 执行耗时: ${end - start}ms`); return result; }; // 返回修改后的属性描述符 return descriptor; }; }
3. 正确使用装饰器
必须将装饰器应用在类的方法上,而非类属性或其他位置:
class ExampleClass { @logExecutionTime() // 保留括号,因为这是工厂函数式装饰器 doSomething() { // 模拟耗时操作 for (let i = 0; i < 1000000; i++) {} } } // 测试调用 const instance = new ExampleClass(); instance.doSomething(); // 控制台会打印方法执行耗时
错误解释
Unable to resolve signature of property decorator when called as an expression:TypeScript误将你的方法装饰器识别为属性装饰器,只要确保装饰器仅用于类方法,这个错误就会消失。Decorator function return type is 'PropertyDescriptor' but is expected to be 'void' or 'any':属性装饰器不允许返回PropertyDescriptor,但方法装饰器支持该返回值,将装饰器移到方法上即可解决此问题,无需强制转换为any。
内容的提问来源于stack exchange,提问作者Arthur Rabelo
相关产品推荐
相关产品推荐

