I am dealing with the following similar types:
class ActionFoo {
action: 'foo';
foo: string;
}
class ActionBar {
action: 'bar';
bar: number;
}
In addition, I have some handler functions for each type of defined "action", such as:
function fooHandler(action: ActionFoo) {
// perform a task
}
function barHandler(action: ActionBar) {
// perform a task
}
Now, the challenge is to create a utility function that can handle all these scenarios. Despite my attempts, the expected types for handlers were incorrect. Here's what I tried:
type ActionHandler<T extends { action: string }, O = any> = (action: T) => O; // defining the type for handlers
function handleAction<T extends { action: string }, O = any>(
action: T,
handlers: {[key in T['action']]: ActionHandler<T, O>}
) {
const handler = handlers[action.action];
if (handler) return handler(action);
throw new Error('not implemented');
}
type Action = ActionFoo | ActionBar;
function run(action: Action) {
return handleAction(action, {
foo: action => fooHandler(action), // TypeScript compiler points out a type error (TS2345) due to missing 'foo' field
bar: action => barHandler(action), // encountering a similar error
});
}