小编luc*_*nca的帖子

打字稿动态类方法

问题

如何将类型检查添加到动态创建的类方法中?

给定一个非常简单的Property类。

class Property {
  value: any;
  name: string;

  constructor(name: string, value: any) {
    this.name = name;
    this.value = value
  }
}
Run Code Online (Sandbox Code Playgroud)

和一Entity堂课

class Entity {
  name: string;
  properties: Property[];


  constructor(name: string, properties: Property[]) {
    this.name = name;
    this.properties = properties;

    this.properties.forEach((p: Property, index: number) => {
      this[p.name] = (value: string): any => {
        if (value) {
          this.properties[index].value = value;
        }
        return this.properties[index].value;
      }
    }, this);
  }
}
Run Code Online (Sandbox Code Playgroud)

重要部分:(this[p.name] = function ... 我们在“转换”时不知道方法的名称)。 …

typescript

5
推荐指数
1
解决办法
4430
查看次数

标签 统计

typescript ×1