【问题标题】:extending a class with a generic T用泛型 T 扩展一个类
【发布时间】:2016-03-14 02:59:45
【问题描述】:

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

【问题讨论】:

    标签: generics typescript


    【解决方案1】:

    你不能,因为类是在编译时定义的,而 animal 类何时编译 T 是未知的。

    但是,您可以在 animal 中定义 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";
      }
    
    }
    

    【讨论】:

    • 感谢您的回复 - 有时在代码中 - 如果你不能,你不能。
    • @MarzSocks 确实如此,但如果您可以向我们提供更多信息,说明您需要此设置的原因,也许我们可以找到更适合您需求的解决方案。 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多