【问题标题】:Get return type of child class in typescript在打字稿中获取子类的返回类型
【发布时间】:2019-06-04 20:02:37
【问题描述】:

我与 Typescript 的斗争是获取作为父类子类的类函数的返回类型。我所能做的就是从父类获取返回类型。

我在最后添加了带有解释性 cmets 的 sn-p。

Link to playground

export interface StepResult<T> {
  data: T;
}

export interface GetCompanyExecute {
  a: number;
}

class BaseStep {
  public async execute(): Promise<StepResult<any>> {
    return { data: {} }
  }
}

class GetCompany extends BaseStep {
  public async execute(): Promise<StepResult<GetCompanyExecute>> {
    return { data: { a: 1 } }
  }
}

// T from Promise<T>
type ThenArg<T> = T extends Promise<infer U> ? U :
  T extends (...args: any[]) => Promise<infer L> ? L :
  T

const getData = async <T extends BaseStep>(StepClass: typeof BaseStep): Promise<ThenArg<T['execute']>['data']> => {
  return 1 as any;
}

(async () => {
  // TODO: I need to get "GetCompanyExecute" here as returned type
  // but it returns any which is return type of BaseStep
  const a = await getData(GetCompany)

  // This is return type I want `await getData(GetCompany)` to be:
  type X = ThenArg<GetCompany['execute']>['data']  
})

【问题讨论】:

    标签: typescript


    【解决方案1】:
    const getData = async <T extends BaseStep>(StepClass: new () => T): Promise<ThenArg<T['execute']>['data']> => {
      return 1;
    }
    
    (async () => {
      const a = await getData(GetCompany) // typeof a === GetCompanyExecute
    })
    

    希望对你有帮助

    【讨论】:

    • 成功了,非常感谢 :) 在我的实际案例中,构造函数有额外的参数,所以我的参数是:StepClass: new (...args: any[]) =&gt; T
    猜你喜欢
    • 2020-06-29
    • 2015-08-10
    • 2021-02-10
    • 2020-05-09
    • 2021-09-18
    • 2022-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多