Typescript类型交集和构造函数

时间:2018-11-09 20:18:07

标签: typescript types type-conversion

我想从调用了其构造函数的片段中创建复合类型。我该怎么做或模仿呢?我不能在扩展中调用super(),也不能使用扩展,因为派生类的构造函数必须包含一个“ super”调用。而且我不知道如何直接创建类型的对象人。

class bar {
  j: number;
  constructor() {
    this.j = 20;
  }
}

class baz {
  i: number;
  constructor() {
    this.i = 10;
  }
}

type person = bar & baz;

class p implements person {
  i: number;
  j: number;
  constructor() {}
}

let _p = new p();
alert(_p.i) //undefined, want it to be 10

1 个答案:

答案 0 :(得分:2)

如果将TypeScript目标语言设置为es6以下,则将类编译为函数。如果您对依赖于在运行时环境中实际实现类的方式的代码感到满意,则可以直接在实现交集的构造函数中直接调用它们:

class p implements person {
  i: number;
  j: number;
  constructor() {
    bar.call(this);
    baz.call(this);
  }
}

不幸的是,这不适用于真正的es6类-如果没有new,则不能调用类构造函数。您将必须实现诸如混合混合的操作,有关示例,请参见this question的答案。