簡體   English   中英

TypeScript 從泛型擴展類

[英]TypeScript extend class from generic

我想用從其父類擴展的類擴展另一個類。 我想覆蓋子類的一些功能,但我希望這個類是通用的。 我怎樣才能做到這一點?

// This definition does not work.
class Foo<T extends Base> extends T {
    // Override child class (T) functions
}

類不能從類型擴展。

您可以:

  • 從另一個類擴展。 對於抽象類,您可以在抽象類中實現具體方法,也可以定義在擴展類中實現的抽象方法。
abstract class Base {
  concreteMethod() {
   // implementation of the concrete method (can still be overwritten in child)
  }
  abstract abstractMethod(): void // must be implemented in child
}

class Foo extends Base {
  abstractMethod() {
    // implementation of the abstract method
  };
}
  • 或從接口實現方法(和屬性)

interface Base {
  prop1: string
  method(): void
}

class Foo implements Base {
  prop1: string;

  constructor() {
    this.prop1 = "hello world"
  }
  method() {
    // implementation of the method
  };
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM