Typescript:转换所有函数参数的通用函数类型

问题描述 投票:2回答:1

在我的项目中,我使用名为Data<X>的通用类型,该通用类型以某种方式转换给定类型X

现在我想创建一个通用函数类型DataFunction<F extends Function>,该函数类型将F的所有参数包装在Data<Parameter>中。

例如,我想要

DataFunction<(a: Type1, b: Type2) => ReturnType>

产生

(a: Data<Type1>, b: Data<Type2>) => ReturnType

我将其转换为已知数量的参数,这是将第一个参数包装在Data<Parameter>中,而使以下参数保持不变:

type DataFunction<T extends (arg0: any, ...args: any[]) => any>  
    = T extends (arg0: infer A, ...args: infer P) => infer R  
        ? (arg0: Data<A>, ...args: P) => R  
        : any;

我的问题是,如何将所有以下参数包装在Data<Paramter>中?我想要这样的东西,它不起作用:

type DataFunction<T extends (arg0: any, ...args: any[]) => any>  
    = T extends (arg0: infer A, ...args: [infer P]) => infer R  
    ? (arg0: Data<A>, ...args: [Data<P>]) => R 
    : any;
typescript typescript-typings type-inference typescript-generics
1个回答
0
投票

这似乎起作用:

type DataFunction<F> = F extends (...args: infer A) => infer R
  ? (...args: { [K in keyof A]: Data<A[K]> }) => R
  : any;
© www.soinside.com 2019 - 2024. All rights reserved.