Daniel Birowsky Popeski
Daniel Birowsky Popeski

Reputation: 9286

Generic type that taps on functions inputs and outputs

Given:

type SomeService = {
    someFunction:      (i: string) => number
    someOtherFunction: (i: string) => string[]
}

I want to have a generic type that results in:

type SomePromisifiedService = {
    someFunction:      (i: string) => Promise<number>
    someOtherFunction: (i: string) => Promise<string[]>
}

Here's some pseudo-code that maybe better explains this:

type PromisifyResults<T extends {}> = 
    { [k in keyof T]: (...T[k].args) => Promise<T[k].output> }

Upvotes: 2

Views: 50

Answers (1)

Aleksey L.
Aleksey L.

Reputation: 37996

Here's how you can do this with conditional types added in typescript 2.8 and generic rest parameters (typescript 3.0):

type PromisifyResults<T> = {
    [K in keyof T]:
        T[K] extends (...args: infer Args) => infer R
        ? (...args: Args) => Promise<R>
        : T[K]
}

Try in playground

Upvotes: 1

Related Questions