Typescript: Generic type of function parameter signature

1.7k Views Asked by At

I try to declare a type which defines a transformation of a function type generating a type with the same arguments but another return type.
The goal is to write a function createAction which expects a function and returns a new function expecting the same arguments as the given one but returning another type.

Input: function expecting a string and a number, returning type R:

const fn = (s: string, n: number) => ({ s, n, b: false })
const g = createAction(fn)

Expected type of g is: function expecting a string and a number, returning type { payload: R }:

typeof g === (s: string, n: number) => ({ payload: { s: string, n: number, b: boolean } })

This would allow me to write another function createActions expecting a function map and returning the same map but with transformed functions:

const t = createActions({
    func1: (s: string) => ({}),
    func2: (n: number, b: boolean) => ({ n }),
});
typeof t === {
    func1: (s: string) => ({ payload: {} }),
    func2: (n: number, b: boolean) => ({ payload: { n: number } }),
}

I could create a type overload with different number of generic arguments to cover a number of different function signatures (see below) but I am looking for a more generic solution which allows inferring the parameter number and types of the given function automatically. Using type overloads makes the function map described above impossible to implement.

A basic solution using generics by hard-coding the number of arguments:

type Transform<D, T1, R> = {
    [K in keyof D]: (p1: T1) => ({
        payload: R;
    });
}
interface CreateActions<D, T1, R> {
    (def: D): Transformed<D, T1, R>;
}

Thanks for the help!

0

There are 0 best solutions below