我与Typescript的斗争是要获得作为父类的子类的类函数的返回类型。我所能实现的就是从父类获取返回类型。
我在最后添加了一段代码,并附有解释性评论。
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']
})
答案 0 :(得分: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
})
希望这可以为您提供帮助