问题
I'm trying to implement the suggestion here, specifically, this function:
function eventAssigner<Handlers extends Record<keyof Handlers, (e: any) => any>,
Discriminant extends keyof any>(
handlers: Handlers,
discriminant: Discriminant
) {
return <Key extends keyof Handlers>(
event: Record<Discriminant, Key> & (Parameters<Handlers[Key]>[0])
): ReturnType<Handlers[Key]> => handlers[event[discriminant]](event);
}
However, eventAssigner
is rejecting the type of the event that I'm providing it, altho it seems to me that the types match. Could you point out where do the types differ?
Here's a playground. Please find the error in the proxyEventAssigner
function.
Here's the rest of the code just in case:
// this is the command comming from outside
type UnauthenticatedCommand<CmdName extends keyof CommandMap> =
CommandMap[CmdName]
& { cmdName: CmdName }
& { jwtToken: string }
// this is the authenticated version of the same command
type AuthenticatedCommand<CmdName extends keyof CommandMap> =
CommandMap[CmdName]
& { authenticatedUser: { id: string } }
& { cmdName: CmdName }
interface CommandMap {
event1: { attr1: string; attr2: number };
event2: { attr3: boolean; attr4: string };
}
const handlers: {
[CmdName in keyof CommandMap]: (e: AuthenticatedCommand<CmdName>) => Promise<void>
} = {
event1: ({attr1, attr2}) => Promise.resolve(),
event2: ({attr3, attr4}) => Promise.resolve(),
};
//-------------------------------------------------
//this function is here just for a bit of context as to
// why the eventAssigner is receiving AuthenticatedCommand<CmdName>
const topHandler =
<CmdName extends keyof CommandMap>(e: UnauthenticatedCommand<CmdName>): Promise<void> =>
proxyEventAssigner(authenticateUser(e));
const proxyEventAssigner =
<CmdName extends keyof CommandMap>(e: AuthenticatedCommand<CmdName>): Promise<void> =>
eventAssigner(handlers, 'cmdName')(e);
const authenticateUser =
<CmdName extends keyof CommandMap>(e: UnauthenticatedCommand<CmdName>): AuthenticatedCommand<CmdName> => {
throw new Error('unimplemented');
};
//-------------------------------------------------------
function eventAssigner<Handlers extends Record<keyof Handlers, (e: any) => any>,
Discriminant extends keyof any>(
handlers: Handlers,
discriminant: Discriminant
) {
return <Key extends keyof Handlers>(
event: Record<Discriminant, Key> & (Parameters<Handlers[Key]>[0])
): ReturnType<Handlers[Key]> => handlers[event[discriminant]](event);
}
来源:https://stackoverflow.com/questions/57925619/why-is-this-param-type-not-assignable-to-the-expected