Typescript: Generic type of function parameter signature

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!

链接地址: http://www.djcxy.com/p/7466.html

上一篇: Haskell中尚未在GHC中实现的可能优化?

下一篇: Typescript:函数参数签名的泛型类型