我正在寻找像这样的接口:
interface Store {
test1(): void
test2(a: string, b: number): RegExp
test3<T>(a: string, b: number): Promise<T>
}
并使用诸如
的映射类型
type AsyncStore = Asyncd<Store>
我想承诺 - 包装函数返回值:
type AsyncStore = Asyncd<Store>
// {
// test1(): Promise<void>
// test2(a: string, b: number): Promise<RegExp>
// test3<T>(a: string, b: number): Promise<T>
// }
我需要对这种“Asyncd
”类型进行改进:
type AnyFunc = (...args: any[]) => any
// wraps a type in a promise, unless it's already a promise
type PromiseWrap<T> = T extends Promise<any> ? T : Promise<T>
// wrap a function's return type in a promise
type PromiseWrapResult<Func extends AnyFunc> =
ReturnType<Func> extends Promise<any>
? (...args: any[]) => ReturnType<Func>
: (...args: any[]) => Promise<ReturnType<Func>>
// perform promise wrapping for each function
type Asyncd<Subject> = {
[Prop in keyof Subject]: Subject[Prop] extends AnyFunc
? (...args: any[]) => PromiseWrap<ReturnType<Subject[Prop]>>
: Subject[Prop]
}
interface MyStore {
test1(): void
test2(a: string, b: number): RegExp
test3<T>(a: string, b: number): Promise<T>
}
type MyAsyncStore = Asyncd<MyStore>
// {
// test1(...args: any[]): Promise<void>
// test2(...args: any[]): Promise<RegExp>
// test3(...args: any[]): Promise<{}>
// }
几乎在那里,但不完全 - 缺少什么:
...args: any[]
相关阅读材料: