用泛型T扩展类 [英] extending a class with a generic T

查看:73
本文介绍了用泛型T扩展类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在TypeScript中,有没有一种方法可以用通用类型扩展类?请参考我的假设场景"示例,在该示例中,我希望我的班级拥有一个名为繁殖"(或其他名称)的属性:

In TypeScript is there a way to extend a class with a generic type? Refer to my "hypothetical scenario" example where I want my class to have property called "breed" (or whatever):

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
  }
}

推荐答案

您不能这样做,因为类是在编译时定义的,并且在 animal 类被编译时是 T 未知.

You can't because classes are defined at compile time, and when the animal class is compiled T is not known.

不过,您可以在动物内定义类型为 T 的属性.

You can however define a property of type T inside animal.

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)
  }

}

我想这取决于您为什么需要动物类为通用类,但是您也可以只用狗扩展动物.

I guess it depends on why you need the animal class to be generic, but you can also just have dog extend animal.

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";
  }

}

这篇关于用泛型T扩展类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆