Creating TypeSafe event emitter wrapper function

I have this file EventTypes.ts:
import type { GuildBan, GuildMember } from 'discord.js';
import type { BanExportOptions, BanImportOptions } from './typeDefs';

export const BUEvents = {
BanListExport: 'banListExport' as const,
BanListImport: 'banListImport' as const,
BotGuildBanAdd: 'botGuildBanAdd' as const,
} as const;

export interface BUEventParams {
[BUEvents.BanListExport]: [payload: BanExportOptions];
[BUEvents.BanListImport]: [payload: BanImportOptions];
[BUEvents.BotGuildBanAdd]: [ban: GuildBan, executor: GuildMember];
}

declare module 'discord.js' {
interface ClientEvents extends BUEventParams {}
}
import type { GuildBan, GuildMember } from 'discord.js';
import type { BanExportOptions, BanImportOptions } from './typeDefs';

export const BUEvents = {
BanListExport: 'banListExport' as const,
BanListImport: 'banListImport' as const,
BotGuildBanAdd: 'botGuildBanAdd' as const,
} as const;

export interface BUEventParams {
[BUEvents.BanListExport]: [payload: BanExportOptions];
[BUEvents.BanListImport]: [payload: BanImportOptions];
[BUEvents.BotGuildBanAdd]: [ban: GuildBan, executor: GuildMember];
}

declare module 'discord.js' {
interface ClientEvents extends BUEventParams {}
}
And I'm trying to create a wrapper function emitBotEvent()
export function emitBotEvent<E extends keyof ClientEvents>(
event: keyof typeof BUEvents,
...args: BUEventParams[E]
) {
container.client.emit(event, args);
}
export function emitBotEvent<E extends keyof ClientEvents>(
event: keyof typeof BUEvents,
...args: BUEventParams[E]
) {
container.client.emit(event, args);
}
What I'm trying to do is, if I put BUEvents.BanListImport, the 2nd parameter of emitBotEvent() function should expect the type [payload: BanImportOptions] And if I put BUEvents.BotGuildBanAdd, the type shuold become [ban: GuildBan, executor: GuildMember] I tried the above way, it doesn't work thonk
1 Reply
MRDGH2821
MRDGH2821OP17mo ago
I think I got resonable amount of type safety with this:
export function emitBotEvent<E extends keyof BUEventParams>(
event: keyof typeof BUEvents,
...args: BUEventParams[E]
) {
container.client.emit(event, ...args);
}
export function emitBotEvent<E extends keyof BUEventParams>(
event: keyof typeof BUEvents,
...args: BUEventParams[E]
) {
container.client.emit(event, ...args);
}
Want results from more Discord servers?
Add your server