In the conclusion of this post, I provide operational code for associating object types with a function that accepts an object containing matching properties. The code snippet I shared results in 'result' being resolved as:
type result = {
GENERATION_COMPLETE: (params: {
generation: ImageGeneration;
}) => void;
IMAGE_VOTE: (params: {
voteForId: string;
}) => void;
SCORE_SCREEN_DONE: () => void;
SUBMIT_THEME: (params: {
theme: string;
}) => void;
THEME_VOTE: (params: {
voteForId: string;
}) => void;
}
However, my intention is to directly map to function parameters rather than an object with properties as a parameter to the function. As a result, the desired expansion of 'result' would look like this:
type result = {
GENERATION_COMPLETE: (
generation: ImageGeneration;
) => void;
IMAGE_VOTE: (
voteForId: string;
) => void;
SCORE_SCREEN_DONE: () => void;
SUBMIT_THEME: (
theme: string;
) => void;
THEME_VOTE: (
voteForId: string;
) => void;
}
Type definition code:
type DreamEventSchema =
| { type: 'GENERATION_COMPLETE', generation: ImageGeneration }
| { type: 'IMAGE_VOTE', voteForId: string }
| { type: 'SCORE_SCREEN_DONE' }
| { type: 'SUBMIT_THEME', theme: string }
| { type: 'THEME_VOTE', voteForId: string }
type OmitType<T> = Omit<T, 'type'> extends infer Omitted ? { [K in keyof Omitted]: Omitted[K] } : never;
type IsEmptyType<T> = keyof T extends never ? true : false;
type EventToFunction<Events extends { type: string }> = {
[E in Events as E['type']]: (
OmitType<E> extends infer Omitted
? IsEmptyType<Omitted> extends true
? () => void
: (params: Omitted) => void
: never
)
}
type result = EventToFunction<DreamEventSchema>;
Do you have any suggestions on how to achieve this?