簡體   English   中英

如何正確應用泛型靜態方法的泛型類型定義?

[英]How to correctly apply generic type definition for generic static methods?

我有以下基類和派生類。

class GenericBase<T = any> {
  static method(id: any) {
    console.log(`${id}: ${this.name}#method`);
  }
  public someProp!: T;
}

class DerivedGeneric extends GenericBase<Date> {}

我正在尋找一種正確應用類型定義的方法,它允許我調用靜態方法。 以下是我迄今為止嘗試過的。

const t1: typeof GenericBase = DerivedGeneric;
t1.method("t1");

type Type<T> = new (...arg: any[]) => T;
const t2: Type<GenericBase> = DerivedGeneric;
t2.method("t2");

對於第一個 ( t1 ),TypeScript 顯示以下錯誤

Type 'typeof DerivedGeneric' is not assignable to type 'typeof GenericBase'.
  Type 'DerivedGeneric' is not assignable to type 'GenericBase'.
    Types of property 'someProp' are incompatible.
      Type 'Date' is not assignable to type 'T'.

對於第二個,它顯示以下錯誤。

Property 'method' does not exist on type 'Type>'.

當然,以下工作沒有任何編譯時錯誤......

const t3: Function = DerivedGeneric;
(t3 as typeof DerivedGeneric).method("t3");

... 以下也是,但現在我們有一個運行時錯誤。

const t4: Function = () => {};
(t4 as typeof DerivedGeneric).method("t4");

如果沒有泛型,第一種方法( typeof *Base* )效果很好。 您可以從這個游樂場鏈接中查看 顯然,所有方法(除了t4 )都在運行時工作,只有編譯時錯誤在困擾我。

有沒有辦法用泛型來糾正打字?

編輯: 鏈接到具有以下類型的操場

type Type<T> = new (...arg: any[]) => T;
type func = Pick<typeof GenericBase, keyof typeof GenericBase> & Type<GenericBase>;

問題是,由於基類有一個泛型類型參數,它的構造函數是一個泛型構造函數。 這將是構造函數簽名的樣子:

const t3 : new <T>(...arg: any[]) => GenericBase<T> = GenericBase

這就是為什么當您嘗試將DerivedGeneric分配給typeof GenericBase您不能,因為DerivedGeneric沒有這樣的泛型構造函數。

如果你只想要一個代表類靜態的類型,你可以使用Pick來擺脫typeof GenericBase的泛型構造函數簽名:

const t1: Pick<typeof GenericBase, keyof typeof GenericBase> = DerivedGeneric; // OK
t1.method("t1");

您還可以創建構造函數返回GenericBase<any>和靜態成員的交集。

type Type<T> =  new (...args: unknown[]) => T;
const t1: Type<GenericBase> & Pick<typeof GenericBase, keyof typeof GenericBase>  = DerivedGeneric;
t1.method("t1");
new t1()

注意:它不適用於...args: any[]any有點特殊,不確定它是如何起作用的,但無論如何都應該首選unknown

暫無
暫無

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

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