从下往上执行,所以name的值会覆盖
// 创建一个泛型:new (...args: any[]) => any 这是一个构造函数,返回 any 类型,接收任意的参数,每个参数的类型不做约束// 现在 constructor 的类型是一个泛型,这个泛型可以通过实例化创建出一个类,这个类应该包含一个构造函数function testDecorator<T extends new (...args: any[]) => any>(constructor: T) {// 对构造函数进行扩展return class extends constructor {name = "zbl";};}@testDecoratorclass Test {name: string;constructor(name: string) {this.name = name;getName() {return this.name;}}}let test = new Test("zws");console.log(test); // class_1 { name: 'zbl' }console.log((test as any).getName());
因为 getName 是装饰器“偷偷”加进来的,所以现在我们调用实例上的方法会报错,通过类型断言的方式可以使其不报错,但这样显然是不对的:
function testDecorator() {return function <T extends new (...args: any[]) => any>(constructor: T) {return class extends constructor {name = "zbl";getName() {return this.name;}};};}// 将装饰器以函数的方式执行,用装饰器去直接修饰 class,生成一个新的类,给到 Testconst Test = testDecorator()(class {name: string;constructor(name: string) {this.name = name;}});let test = new Test("zws");// 不报错,并且有提示console.log(test.getName());
