Reducer
Reducer

Reputation: 760

Typescript: Generic function type transforming all function paramters

In my project I'm using a generic type called Data<X> that is transforming the given type X in a certain way.

Now I want to create a generic function type DataFunction<F extends Function> that is wrapping all parameters of F in Data<Parameter>.

For example I want

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

to result in

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

I made it to transform a known number of parameters, this here is wrapping the first Paramter in Data<Parameter>, leaving the following ones unchanged:

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;

My question is, how can I also wrap all following paramters in Data<Paramter>? I want something like this, which is not working:

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;

Upvotes: 2

Views: 113

Answers (1)

georg
georg

Reputation: 214949

This seems to work:

type DataFunction<F> = F extends (...args: infer A) => infer R
  ? (...args: { [K in keyof A]: Data<A[K]> }) => R
  : any;

PG

Upvotes: 2

Related Questions