从传递的函数对象生成多个函数参数

时间:2019-10-07 09:30:25

标签: typescript typescript-typings typescript-generics

我正在创建一个用于从传递的函数中自动生成函数的工具。 如何使打字稿键入不混合传递函数的参数

TypeScript版本:v3.6.3

type IActions<AS extends IDefinitions<AS>> = 
    Record<keyof AS, (...args: Parameters<AS[keyof AS]>) => any>;

export type IDefinitions<D> = Record<keyof D, (...args: any[]) => Generator>;

function creator <D extends IDefinitions<D>>(def: D): IActions<D> {
    return {} as any;
}


const u = creator({
    *getUser(name: string) {
        yield Promise.all([]);
    },
    *test(id: number, name: string) {
        yield Promise.race([]);
    },
})

// The function type is: getUser(...args: [string] | [number, string]): any
u.getUser()

也可以看到playground

似乎应该返回正确的参数,如下所示:

// getUser(name: string): any
u.actions.getUser('test');

// getUser(id: number, name: string): any
u.actions.test(123, 'test');

0 个答案:

没有答案