Cómo pasar de manera segura argumentos a un closure en un objeto en TypeScript
El siguiente código funciona bien, pero no pude quitar @ts-ignore.
const actions = {
a: (x: number): number => x,
b: (x: number, y: string) => x,
c: (x: number, y: string) => y,
};
interface Action<K extends keyof typeof actions> {
type: K;
payload: ReturnType<typeof actions[K]>;
}
function action<K extends keyof typeof actions, Args extends Parameters<typeof actions[K]>>(
type: K,
...args: Args
): Action<K> {
return {
type,
// FIXME: remove @ts-ignore.
// @ts-ignore
payload: actions[type](...args),
};
}
const a: Action<'a'> = { type: 'a', payload: 1 };
const b: { type: 'b'; payload: number } = action('b', 42, 'hello');
const c: { type: 'c'; payload: string } = action('c', 42, 'hello');