[英]typescript class decorator: typing properties defined in decorator function
bar is a simple class decorator that adds a property to the class Foo. 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);
The only console log that causes an error is the first, Foo.inDecorator, the inclusion of which in ts 1.5.3 gives 导致错误的唯一控制台日志是第一个,Foo.inDecorator,包含在ts 1.5.3中的内容
Property 'inDecorator' does not exist on type 'typeof Foo'.
As far as I can tell inDecorator should be defined on the prototype of Class Foo and should be available on Foo as if it were a static prop. 据我所知,inDerator应该在Class Foo的原型上定义,并且应该在Foo上可用,就像它是静态道具一样。 Running the resulting js file reveals undefined for the prototype access as well as on the new foo object, however Foo.inDecorator prints correctly even though it is the source of the error. 运行生成的js文件显示原型访问以及新foo对象的未定义,但是Foo.inDecorator即使它是错误的来源也能正确打印。 To be more clear, we get 更清楚的是,我们得到了
in decorator
undefined
a string
undefined
Any ideas on how to correctly type/add a static prop or method? 关于如何正确输入/添加静态道具或方法的任何想法?
Thanks! 谢谢!
Edited this as I originally overlooked the fact that prototype access, Foo.prototype.inDecorator was not working. 编辑这个,因为我最初忽略了原型访问,Foo.prototype.inDecorator无法正常工作的事实。
Within the decorator target
refers to the function— Foo
—rather than the prototype— Foo.prototype
. 在装饰target
指的是功能- Foo
-rather比原型的Foo.prototype
。
So in the decorator doing target.inDecorator = ...
is the same as Foo.inDecorator = ...
and not Foo.prototype.inDecorator = ...
. 因此在装饰器中执行target.inDecorator = ...
与Foo.inDecorator = ...
相同而不是Foo.prototype.inDecorator = ...
Here's one way of doing it: 这是一种方法:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.