TheAschr
TheAschr

Reputation: 973

Arbitrary number of function overloads

I'm using the following code to overload a function defining an 'event' handler.

export function on(eventName: 'created', eventCallback: (args: { uuid: string }) => void): any;
export function on(eventName: 'updated', eventCallback: (args: { id: number }) => void): any;
export function on(eventName: any, eventCallback: any) {

}

Is there any way I can template this process so that I can overload this function with an abitruary number of events:

type Events = ['created',{uuid: string}] | ['updated',{id: number}];

export function on(eventName: any, eventCallback: any) {

}

Upvotes: 0

Views: 25

Answers (1)

jcalz
jcalz

Reputation: 330571

You can convert a union of tuples into an intersection of function signatures via something like UnionToIntersection and that would be a direct analog of overloads.

However in this case I'd be inclined to use the union of tuples directly as a rest parameter of a single function signature:

type Events = ['created', { uuid: string }] | ['updated', { id: number }];

export function on(...[eventName, eventCallback]: Events) {

}

on('created', { uuid: "" }); // okay
on('updated', { id: 1 }); // okay
on('created', { id: 1 }); // error

Maybe that would work for you. Hope that helps; good luck!

Playground link to code

Upvotes: 1

Related Questions