Javascript typescript类装饰器:在装饰器函数中定义的类型属性
bar是一个简单的类装饰器,它向类Foo添加属性Javascript typescript类装饰器:在装饰器函数中定义的类型属性,javascript,class,typescript,decorator,typeof,Javascript,Class,Typescript,Decorator,Typeof,bar是一个简单的类装饰器,它向类Foo添加属性 function bar(target) { target.inDecorator = 'in decorator'; } @bar class Foo { inClass:string; inDecorator:string; constructor() { this.inClass = 'a string'; } getInClass() { return t
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'.
据我所知,indcorator应该在类Foo的原型上定义,并且应该在Foo上可用,就像它是一个静态道具一样。运行生成的js文件会显示原型访问以及新foo对象上的未定义,但是foo.inDecorator打印正确,即使它是错误的来源。更清楚地说,我们得到了
in decorator
undefined
a string
undefined
关于如何正确键入/添加静态道具或方法有何想法
谢谢
编辑这篇文章是因为我最初忽略了prototype access、Foo.prototype.inDecorator不工作的事实。在decorator
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
这肯定是可行的,但它似乎有很多多余的代码,当然不是直观的。如果indcorator与Foo.indcorator相同,为什么它必须在基类上?如果要使用static newProp=“new string”直接在Foo上添加一个静态prop,它是否也必须以这种奇怪的方式键入?没有办法实现接口而不是扩展类?或使用静态索引器:字符串;在Foo课上?我自己的实验表明答案是否定的。不过谢谢你的有效解决方案!我只希望typescript有一个更简洁的方法!谢谢你解决这个问题!在简单地从decorator添加一个道具的情况下,我想它确实可以归结为静态indcorator:string;在Foo中,如果您没有在接口中键入内容或在原型中添加内容。我发誓我试过了经典继承在这里要干净得多,但我正在尝试编写一个angular 1.x,它看起来和感觉都像2.0,使用组件和视图装饰器来执行大量的指令逻辑。也许有点傻。这些函数还做了很多其他装饰特定的工作,只是似乎无法在ts中键入道具。谢谢!