【发布时间】:2018-01-22 18:52:22
【问题描述】:
这是我的代码示例:
function enumerable(value: boolean) {
return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {
descriptor.enumerable = value;
};
}
class A {
@enumerable(false)
a: number = 1
b: number = 2
myMethod () {}
}
const a = new A()
无论我尝试什么,我都会得到:
D:(real path removed)/first-try-typescript>tsc --emitDecoratorMetadata --experimentalDecorators decorators.ts
decorators.ts(8,3): error TS1240: Unable to resolve signature of property decorator when called as an expression.
我已经尝试了相同 stackoferflow 问题建议中的所有内容:
- 在 tsconfig 中添加 emitDecoratorMetadata 和实验性装饰器
- 运行 tsc --emitDecoratorMetadata --experimentalDecorators
- 添加
:any标记装饰器函数返回值 - 添加
descriptor: TypedPropertyDescriptor<any>类型
我总是收到这个错误。在终端和 Webstorm 代码提示中。方法装饰器 - 相同的东西(参见下面的示例)。
function test(target: Object,
propertyKey: string,
descriptor: TypedPropertyDescriptor<any>): any {
return descriptor;
}
class A {
a: number = 1
b: number = 2
@test
myMethod () {}
}
const a = new A()
【问题讨论】:
-
你想要的结果是什么?装饰器应该应用于函数/方法,您尝试做的似乎是将方法混合到类中
-
@NickTomlin -- 不正确,装饰器也可以应用于属性。
-
@JohnWeisz 啊,有趣,那我的错!
-
@JohnWeish - 我尝试为方法应用装饰器 - 结果相同。请参阅更新的示例。根据这篇文章medium.com/google-developers/…,我认为按照我的方式添加道具装饰器是可以的
标签: javascript typescript