用TypeScript自动创建带有字段的类

时间:2019-05-27 09:25:00

标签: typescript

查看我的代码:

interface IMyInterface{
  a:string
  b:string
  c:number
  //and more...
}
class MyClass extends IMyInterface{ //err 1
  //the class has all fields from IMyInterface
  constructor(opt:IMyInterface){
    for(let key in opt){
      this[key]=opt[key] //err2
    }
  }
  myOtherMethods(){}
}

我希望一个类具有从接口(从HTTP请求返回)扩展的所有字段,并使用值自动构造它。上面的代码有2个错误:

  1. 类无法扩展接口,但是如果使用implements,则需要再次编写该类中的所有字段和类型。

  2. key的类型是字符串,我无法在this上访问它的字段。

2 个答案:

答案 0 :(得分:0)

也许将IMyInterface重写为类,然后扩展例如

class BaseClass {
  public a: string = 'foo';
}

class MyClass extends BaseClass {
  constructor() {
    super();
    console.log(this.a); // 'foo'
  }

  public someMethod() {
    console.log(this.a); // 'foo'
  }
}

接口仅是类型信息。它们没有任何语义含义(如默认值)

答案 1 :(得分:0)

泛型类型

<<<"$x"

如果您需要它们完全是类字段,则可以检查this solution