I'm struggling coming up with a good structure for a Command -> Response generic.
My goal is to have a function accept a command from a list of commands based on a Type or Interface, and use that interface to infer the response type.
So far I've managed to correctly infer the expected data based on the type property, but I can't seem to wrap my head around inferring the return type of the generic.
Any pointers towards similar examples are very much welcome! I haven't been able to find much
Code example: TypeScript Playground
type MappedData<E, T extends keyof E> = E[T];
type MappedType<E> = {
[K in keyof E]: {
type: K;
data: MappedData<E, K>;
};
}[keyof E];
interface ServerCommandInterface<T> {
_res?: T;
}
interface TestCommandA extends ServerCommandInterface<{responseA: boolean}> {
param_a: string;
}
interface TestCommandB extends ServerCommandInterface<{responseB: boolean}> {
param_b: string;
}
interface Commands {
command_a: TestCommandA;
command_b: TestCommandB;
}
function execute<C extends MappedType<Commands>>(command: C): typeof command.data._res {
// Logic (HTTP call or similar) that would result in _res type
return null as any;
}
const result = execute({
type: 'command_a',
data: {
param_a: 'param',
}
});
console.log(result.responseA); // I expect this to be a boolean