I am trying to type my event API as such:
type Apple = {
seeds: number;
}
type Peach = {
weight: number;
}
interface AddAppleEvent {
apple: Apple;
}
interface AddPeachEvent {
peach: Peach;
}
interface EventMap {
"addApple": AddAppleEvent;
"addPeach": AddPeachEvent;
}
class EventApi{
on<K extends keyof EventMap>(type: K, listener: (ev: EventMap[K]) => any): void{
}
}
const api = new EventApi();
api.on("addApple", (evt) => {
console.log(evt.apple);
});
This works wonder: Typescript knows what is in my evt variable from the name of the event I am registering on.
But: I would like ot be able to register to an array of events, and type the result (which will be a composition of the types of each events):
api.on(["addApple", "addPeach"], ({apple, peach}) => {
if(apple) {
// do something
}
if(peach) {
// do something else
}
})
Unfortunately I cant find a way to iterate over an array of keys from an interface to build an union of all the values referred.
Any idea ?
Here is a link to the typescript playground with the example above
-----EDIT----
Just summing up the great answers I got for this post:
- If you want union: checkout this playground by @t-j-crowder
- If you want intersection: checkout this playground by @jcalz
Thanks a lot guys:)