我最终放弃了一个通用的解决方案。。。这是我能得到的最接近的:
我会在参数中做一个并集运算。这将允许我在需要时自动完成。
稍后,在dispatcher中,我将创建一个返回类型,并显式地传递它。
见下表:
这允许我在dispatcher和registrar中自动完成它。
export type MediatorCommands =
| {
type: "CREATE_ROLE";
arg: CreatePermissionCommand | typeof createPermissionCommandHandler;
}
| {
type: "CREATE_NEW_INSTITUTION_ACCOUNT";
arg:
| CreateNewInstitutionAccountCommand
| typeof CreateNewInstitutionAccountCommandHandler;
}
那么我的职责是:
// This is hacky... but it works!
let commands: {
[x: string]: Function;
} = {};
export function registerCommand({ type, arg }: MediatorCommands) {
commands[type] = arg as Function;
}
export async function dispatchCommand<TResult>({
type,
arg,
}: MediatorCommands) {
logTime(type);
return commands[type](arg) as Promise<TResult>;
}
然后,要注册命令:
registerCommand({
type: "CREATE_ROLE",
arg: createPermissionCommandHandler,
});
然后,你可以这样做:
await dispatch<CreatedRoleRT>({
type: "CREATE_ROLE",
arg: {
tenantId,
employeeId,
},
});
这个
CreatedRoleRT
type CreatedRoleRT = ReturnType<typeof createPermissionCommandHandler>;
这并不完美。。。但它是有效的!