【问题标题】:change the class definition with TS decorator使用 TS 装饰器更改类定义
【发布时间】:2022-08-15 22:11:05
【问题描述】:

我试图重现@Getters通用 Java 库 Lombok。结果将是:

@Getters()
export class Example {
  private property: string;
}
const test = new Example();
console.log(test.getProperty());

为此,我尝试通过使用 TS 装饰器覆盖它来更改 js 类定义:

import { capitalize } from \"lodash\";

export const Getters = () => <T extends {new(...args:any[]):{}}>(constructor:T) => {  
  return class extends constructor {
    constructor(...args: any[]) {
      super(...args);
      const props = Reflect.ownKeys(this);
      props.forEach((prop: string) => {
        const capitalizedKey = capitalize(prop);
        const methodName = `get${capitalizedKey}`;
        Reflect.defineProperty(this, methodName, { value: () => this[prop], configurable: false, enumerable: false });
      });
    }
  }
}

目前,我有这个错误X 类型上不存在 X 属性。

但我可以得到这样的结果:

console.log(test[\'getProperty\']())

有人知道如何用 TS 装饰器更改类定义吗?

游乐场:https://typescript-lodash-playground-1fuxpz.stackblitz.io

    标签: javascript typescript decorator


    【解决方案1】:

    如文档中所述。装饰器不要更改类型:https://www.typescriptlang.org/docs/handbook/decorators.html#class-decorators

    【讨论】:

      猜你喜欢
      • 2022-07-21
      • 2022-08-15
      • 2020-02-26
      • 2022-11-28
      • 2018-11-13
      • 2020-05-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多