簡體   English   中英

推斷 class 泛型屬性方法返回類型

[英]Infer class generic property method return type

我無法推斷 class 泛型屬性的返回類型。

我有一個有效的簡單設置:

class A<T extends B> {
  constructor(public b: T) {}

  getB() {
    return this.b
  }

  bMethodResult() {
    return this.b.methodOne()
  }
}

class B {
  methodOne() {
    return { status: 'ok' }
  }
}

const aOne = new A(new B())

aOne.getB() // :B

aOne.bMethodResult() // {status:string}

如您所見,TS 正確推斷了aOne.bMethodResult()的返回類型。 但是,如果我嘗試使用不同的方法簽名傳入B class 的子代,則 TS 不會將返回類型更新為B子代 class 方法。

class BChild extends B {
  methodOne() {
    return { status: 'ok', data: true }
  }
}

const aTwo = new A(new BChild())

aTwo.getB() // : BChild // ok

aTwo.bMethodResult() // : {status:string }
// I want it to be {status:string, data:boolean}

有沒有辦法獲得class 的返回類型?

TS游樂場

您可以通過向bMethodResult添加返回類型來做到這一點:

class A<T extends B> {
  // ...

  bMethodResult(): ReturnType<T['methodOne']> {
    return this.b.methodOne() as ReturnType<T['methodOne']>
  }
}

// ...

aTwo.bMethodResult() // : {status:string, data: boolean}

但是,這需要類型斷言,因為 TypeScript 將this.b.methodOne()推斷為{status: string}而不是ReturnType<T['methodOne']>

游樂場鏈接

暫無
暫無

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

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