TypeScript类型映射:如何包装函数返回值?

时间:2018-05-19 02:00:11

标签: typescript mapped-types conditional-types

我正在寻找像这样的接口:

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[]
  • 泛型不能在转换中存活(通知test3)..有没有办法通过类型映射来保留函数泛型?

相关阅读材料:

0 个答案:

没有答案