I have an object that contains keys paired with functions as their values. My goal is to create a function where only the keys can be assigned if the corresponding value includes a callback function as its last parameter.
The callback function must take only one argument and return void.
interface Events {
'valid0': (data: string, cb: () => void) => void, // valid
'valid1': (data: number, cb: (data: string) => void) => void, // valid
'invalid0': (data: string, cb: () => string) => void, // invalid return type of callback
'invalid1': (data: string, cb: (string: string, number: number) => void) => void, // invalid number of callback arguments
}
type EventsWithCallback<E> = ???
type testFunction<Events> = (EventName: EventsWithCallback<Events>) => void
I am struggling to define the EventsWithCallback type. The error I encounter is:
Type 'T[P]' does not satisfy the constraint '(...args: any[]) => void'
. It does make sense in a way. I attempted to type T as Record<string, (...args: any) => void>
but then it matches all strings.
type Last<T extends any[]> = T extends [...any, infer Last] ? Last : any;
type EventsWithCallback<T> = keyof { [P in keyof T as Last<Parameters<T[P]>> extends Function ? P : never]: T[P] };
In addition, extends Function
matches any function as well as any type.
Thank you for any assistance. I hope the issue is clear.