原文链接: ts 类装饰器的不足
上一篇: ts 装饰器
下一篇: js worker 快速传递数组
https://www.tslang.cn/play/index.html
使用函数调用是可以增强方法的
interface IRun {
age: number;
run(): void;
}
function testDecorator() {
return function<T extends new (...args: any[]) => any>(constructor: T) {
console.log('1');
return class extends constructor implements IRun {
name = 'lee';
age = 13;
getName() {
return this.name;
}
run() {}
};
};
}
const Test = testDecorator()(
class {
name: string;
constructor(name: string) {
this.name = name;
}
}
);
const test = new Test('d');
console.log(test.getName());
如果用装饰器的写法, 虽然执行时有, 但是提示确实没有的, 会报错....
可以用下的方法重新创建类,或者强转any
interface IRun {
age: number
run(): void
}
function testDecorator() {
return function <T extends new (...args: any[]) => any>(constructor: T) {
console.log("1")
return class extends constructor implements IRun {
name = "lee"
age = 13
getName() {
return this.name
}
run() { }
}
}
}
@testDecorator()
class Test {
name: string
constructor(name: string) {
this.name = name
}
}
const test = new Test("d")
console.log(test.getName())
const Test2 = testDecorator()(
class {
name: string;
constructor(name: string) {
this.name = name;
}
}
);
const test2 = new Test2("d")
console.log(test2.getName())