2

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!

remolueoend
  • 71
  • 1
  • 5
  • 2
    Appears to be impossible at the moment. See the discussion in https://github.com/Microsoft/TypeScript/issues/5453, https://github.com/Microsoft/TypeScript/issues/12342 and https://github.com/Microsoft/TypeScript/issues/212 – artem Sep 18 '17 at 16:16

0 Answers0