簡體   English   中英

Typescript:class 類型的實例

[英]Typescript: Instance of class type

我有像 A_Type 這樣的A_Type的類型?

class A {
  constructor(public a: string) {}
}

type A_Type = {new (a: string): A}

我想獲取A_Type構造函數實例的類型,這樣我就可以顯式輸入這個 function

class A {
  constructor(public a: number) {}
}
//                                              ** not working **
function f<W extends { new(a: number): A }>(e: W): instanceof W {
  return new e(2)
}

let w = f(A)

我基本上是在typescript中尋找typeof的反向操作。

您可以使用內置的InstanceType<T>實用程序來執行此操作

class A {
    constructor(public a: number) { }
}

// declare that the return value of the class constructor returns an instance of that class
function f<W extends { new(a: number): InstanceType<W> }>(e: W) {
    return new e(2) // return type is automatically inferred to be InstanceType<W>
}

let w = f(A) // w: A

游樂場鏈接

function f<W extends { new(a: number): any }, R extends W extends { new(a: number): infer U } ? U : never>(e: W): R {
  return new e(2)
}

您需要使用 generics 來提取返回類型。

但是,如果您總是期望A的實例,則可以將其簡化為

function f<W extends { new(a: number): A }>(e: W): A {
  return new e(2)
}

我會 go 使用以下內容:

type Constructor<X> = {new (a: number): X}

function f<X>(e: Constructor<X>): X {
  return new e(2)
}

const w = f(A)

暫無
暫無

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

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