代码之家  ›  专栏  ›  技术社区  ›  gleb.kudr

Typescript类型交集和构造函数

  •  0
  • gleb.kudr  · 技术社区  · 7 年前

    我想从调用了构造函数的片段中生成复合类型。我怎么做或模仿这个?我不能在inImplementation中调用super(),也不能使用extend-since 我不知道如何直接创建person类型的对象。

    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 回复  |  直到 7 年前
        1
  •  2
  •   artem    7 年前

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

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

    不幸的是,这不适用于真正的es6类-您不能在没有 new this question 例如。

    推荐文章