bar 是一个简单的类装饰器,它向类 Foo 添加一个属性。
function bar(target) {
target.inDecorator = 'in decorator';
}
@bar
class Foo {
inClass:string;
inDecorator:string;
constructor() {
this.inClass = 'a string';
}
getInClass() {
return this.inClass;
}
}
console.log(Foo.inDecorator);
console.log(Foo.prototype.inDecorator);
const foo = new Foo();
console.log(foo.getInClass());
console.log(foo.inDecorator);
唯一导致错误的控制台日志是第一个,Foo.inDecorator,在 ts 1.5.3 中包含它给出
Property 'inDecorator' does not exist on type 'typeof Foo'.
据我所知,inDecorator 应该在类 Foo 的原型(prototype)上定义,并且应该在 Foo 上可用,就好像它是静态 Prop 一样。运行生成的 js 文件显示未定义的原型(prototype)访问以及新的 foo 对象,但是 Foo.inDecorator 打印正确,即使它是错误的来源。更清楚地说,我们得到
in decorator
undefined
a string
undefined
关于如何正确输入/添加静态属性或方法有什么想法吗?
谢谢!
编辑这个是因为我最初忽略了原型(prototype)访问 Foo.prototype.inDecorator 不起作用的事实。
最佳答案
在装饰器中,target
指的是函数——Foo
——而不是原型(prototype)——Foo.prototype
。
所以在装饰器中执行 target.inDecorator = ...
与 Foo.inDecorator = ...
相同,而不是 Foo.prototype.inDecorator = ...
。
这是一种实现方式:
interface BarStatic {
new(): BarInstance;
inDecorator: string;
}
interface BarInstance {
inDecorator: string;
}
function bar(target: BarStatic) {
target.inDecorator = 'static';
// note that prototype will be `any` here though
target.prototype.inDecorator = 'instance';
}
@bar
class Foo {
static inDecorator: string; // required
inDecorator: string; // required
inClass: string;
constructor() {
this.inClass = 'a string';
}
getInClass() {
return this.inClass;
}
}
console.log(Foo.inDecorator); // static
console.log(Foo.prototype.inDecorator); // instance
const foo = new Foo();
console.log(foo.getInClass()); // a string
console.log(foo.inDecorator); // instance
关于javascript - typescript 类装饰器 : typing properties defined in decorator function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31757926/