用通用T扩展一个类

时间:2016-03-13 18:43:45

标签: generics typescript

在TypeScript中有没有办法用泛型类型扩展类?参考我的"假设场景"例如,我希望我的班级拥有名为"品种" (或其他):

interface dog {
  breed: string;
}

export class animal<T> extends T {
  legs: number;
}

export class main {
  private mydog: animal = new animal<dog>();

  constructor() {
    this.mydog.legs = 4;
    this.mydog.breed = "husky"; //<-- not conventionally possible, but basically want to acheive this
  }
}

1 个答案:

答案 0 :(得分:0)

你不能因为类是在编译时定义的,当编译动物类时 T 是未知的。

但您可以在动物中定义 T 类型的属性。

interface dog {

  breed: string;

}

export class animal < T > {
  actual: T;
  legs: number;
}

export class main {

  private mydog: animal < dog > = new animal < dog > ();

  constructor() {

    this.mydog.legs = 4;
    this.mydog.actual.breed = "husky"; // this will fail because actual is undefined (you must set it too)
  }

}

我想这取决于为什么你需要动物类是通用的,但你也可以只有狗延伸动物。

export class animal {
  legs: number;
}

class dog extends animal {
  breed: string;
}

export class main {

  private mydog: dog = new dog();

  constructor() {

    this.mydog.legs = 4;
    this.mydog.breed = "husky";
  }

}