如何将装饰器应用到现有类

问题描述 投票:0回答:1

我在外部包中有A类

class A {
  mess: string;
}

还有我的房产装饰师

function test(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
  target.propertyKey = 'test';
};

我想将我的装饰器

test
应用到A类,但我无法获得A类的反射来应用

test(reflectionOfClassA, attributeKey)

如何获得A类反映?我无法更新 A 类的代码,因为它是从其他包导入的

javascript typescript reflection reflect-metadata
1个回答
0
投票

我不确定您想要实现的目标是否被认为是一个好的模式,但您可以使用 Mixins 添加另一个属性。类装饰器不能添加额外的属性,只能修改现有的属性。

class A {
  mess: string;
}

function test<T extends {new (...args: any[]): {}}>(constructor: T) {
  return class extends constructor {
    customProperty = "customProperty";
  };
}

const a = new (test(A))();

console.log(a.customProperty);

TypeScript 游乐场

© www.soinside.com 2019 - 2024. All rights reserved.