如何在TypeScript中声明类装饰器并在父类内读取其值?
完全可行,以下是实现方案
首先实现CollectionName装饰器,它的作用是给目标类挂载一个静态属性,存储传入的集合名称:
function CollectionName(name: string) { return function(target: Function) { // 给类构造函数添加静态属性collectionName target.collectionName = name; }; }
接着修改父类Base的readCollectionName方法,通过this.constructor获取子类的构造函数,进而读取装饰器挂载的静态属性:
abstract class Base{ readCollectionName(): string{ // 通过类型断言告诉TypeScript构造函数上存在collectionName属性 return (this.constructor as typeof Base & { collectionName: string }).collectionName; } }
子类代码保持你的原有写法:
@CollectionName('person') class Child extends Base{ name: string; } const c = new Child(); console.log(c.readCollectionName()) // 输出: person
原理说明
类装饰器在运行时会接收目标类的构造函数作为参数,我们可以直接给这个构造函数添加静态属性。父类实例的this.constructor指向的是子类的构造函数,因此能直接读取到装饰器赋予的属性值。如果需要处理未添加装饰器的情况,可以给返回值加个默认兜底,比如|| 'default'。
内容的提问来源于stack exchange,提问作者SexyMF
相关产品推荐
相关产品推荐

