假设:
type SomeService = {
someFunction: (i: string) => number
someOtherFunction: (i: string) => string[]
}
我想要一个通用类型导致:
type SomePromisifiedService = {
someFunction: (i: string) => Promise<number>
someOtherFunction: (i: string) => Promise<string[]>
}
这里有一些伪代码可能更好地解释了这一点:
type PromisifyResults<T extends {}> =
{ [k in keyof T]: (...T[k].args) => Promise<T[k].output> }
答案 0 :(得分:0)
现在,在typescript 2.8中添加conditional types,您可以实现非常接近的目标:
type PromisifyResults<T> = {
[K in keyof T]: T[K] extends ((i: infer I) => infer R) ? (i: I) => Promise<R> : never;
}
此版本仅支持具有单个输入参数的方法,但您可以对其进行扩展以支持更多:
type PromisifyResults<T> = {
[K in keyof T]:
T[K] extends ((i: infer I) => infer R)
? (i: I) => Promise<R>
: T[K] extends ((i1: infer I1, i2: infer I2) => infer R)
? (i1: I1, i2: I2) => Promise<R>
: never;
}