Is it possible to infer the type of a second argument, which is a callback in my case, based on the enum value of the first argument.
I am having an issue where I am not able to infer the type for callback
in the on
function based on the eventName
enum value.
<code>enum EventsEnum {
JOIN = "join",
LEAVE = "leave",
}
export interface EventsCallback {
[EventsEnum.JOIN]: (users: User[]) => void;
[EventsEnum.LEAVE]: (userId: string) => void;
}
export type Listener = {
[eventName in EventsEnum]?: { callback: EventsCallback[eventName] };
}
this.listeners: Listener = {}
function on(event: EventsEnum, callback: EventsCallback[EventsEnum]) {
if (!listener[eventName]) {
// I am having an issue here, this won't compile
this.listener[eventName] = {callback: callback}
}
}
// somewhere in the code
if (eventName === EventsEnum.JOIN) {
listener[eventName].callback(users);
} else { ... }
on(EventsEnum.JOIN, (users) => {
//users here will infer correct type to User[]
});
on(EventsEnum.LEAVE, (user) => {
//user here will infer correct type to string
})
</code>
<code>enum EventsEnum {
JOIN = "join",
LEAVE = "leave",
}
export interface EventsCallback {
[EventsEnum.JOIN]: (users: User[]) => void;
[EventsEnum.LEAVE]: (userId: string) => void;
}
export type Listener = {
[eventName in EventsEnum]?: { callback: EventsCallback[eventName] };
}
this.listeners: Listener = {}
function on(event: EventsEnum, callback: EventsCallback[EventsEnum]) {
if (!listener[eventName]) {
// I am having an issue here, this won't compile
this.listener[eventName] = {callback: callback}
}
}
// somewhere in the code
if (eventName === EventsEnum.JOIN) {
listener[eventName].callback(users);
} else { ... }
on(EventsEnum.JOIN, (users) => {
//users here will infer correct type to User[]
});
on(EventsEnum.LEAVE, (user) => {
//user here will infer correct type to string
})
</code>
enum EventsEnum {
JOIN = "join",
LEAVE = "leave",
}
export interface EventsCallback {
[EventsEnum.JOIN]: (users: User[]) => void;
[EventsEnum.LEAVE]: (userId: string) => void;
}
export type Listener = {
[eventName in EventsEnum]?: { callback: EventsCallback[eventName] };
}
this.listeners: Listener = {}
function on(event: EventsEnum, callback: EventsCallback[EventsEnum]) {
if (!listener[eventName]) {
// I am having an issue here, this won't compile
this.listener[eventName] = {callback: callback}
}
}
// somewhere in the code
if (eventName === EventsEnum.JOIN) {
listener[eventName].callback(users);
} else { ... }
on(EventsEnum.JOIN, (users) => {
//users here will infer correct type to User[]
});
on(EventsEnum.LEAVE, (user) => {
//user here will infer correct type to string
})