【问题标题】:Generic type that taps on functions inputs and outputs利用函数输入和输出的通用类型
【发布时间】:2018-06-06 20:11:05
【问题描述】:

给定:

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> }

【问题讨论】:

    标签: typescript generics typescript2.0


    【解决方案1】:

    以下是在 typescript 2.8 和 generic rest parameters (typescript 3.0) 中添加 conditional types 的方法:

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

    Try in playground

    【讨论】:

    • @Birowsky 查看更新的答案 - 简化且不限于函数参数计数
    猜你喜欢
    • 1970-01-01
    • 2020-07-02
    • 1970-01-01
    • 2017-11-01
    • 1970-01-01
    • 2021-04-08
    • 2011-11-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多