Skip to content

One handler, several commands

Answer several slash commands or subcommands from one handler class, and branch on the route that ran.

Two commands that share most of their work become two handler classes, plus a helper you import into both. Instead, just handle both in a single handler class. You write the list in the decorator and again in the generic.

src/handlers/Moderation.ts
import { SlashHandler, SlashRoute } from '@seedcord/gateway';

@SlashRoute('ban', 'kick')
export class Moderation extends SlashHandler<'ban' | 'kick'> {
    public async execute(): Promise<void> {
        await this.match({
            ban: async (options) => {
                const reason = options.getString('reason');
                await this.reply(`Banned. ${reason ?? ''}`);
            },
            kick: async () => {
                await this.reply('Kicked.');
            }
        });
    }
}

Each case receives that route's own options, so reason is there in the ban case even though kick never declares it.

Subcommands work the same way

List a route with a slash the same as any other. One handler can answer every leaf of a command.

src/handlers/Role.ts
@SlashRoute('role/add', 'role/remove')
export class Role extends SlashHandler<'role/add' | 'role/remove'> {
    public async execute(): Promise<void> {
        await this.match({
            'role/add': (options) =>
                this.reply(`Gave ${options.getRole('role').name}.`),
            'role/remove': (options) =>
                this.reply(`Took ${options.getRole('role').name}.`)
        });
    }
}

Options every route shares

this.options on the class holds the options every route in the list declares. ban and kick both take target, so it's there.

const target = this.options.getUser('target');
const target: User

An option only one route declares stays out.

@SlashRoute('ban', 'kick')
class Moderation extends SlashHandler<'ban' | 'kick'> {
    public async execute(): Promise<void> {
        const reason = this.options.getString('reason');
Property 'getString' does not exist on type 'SlashOptions<"ban" | "kick", "cached">'.
} }

reason belongs to ban alone, so you read it inside that case.

Both lists must carry the same routes

Adding a route to one list and forgetting the other is a compile error on the decorator line. TypeScript opens that error on a generic line about the decorator. The sentence you want sits a couple of lines further in:

SlashHandler declares a route that the SlashRoute decorator does not list

Most seedcord type errors carry a plain sentence like that one somewhere in the type noise. Read past the first line and look for it.

@SlashRoute('ban')
Unable to resolve signature of class decorator when called as an expression. Argument of type 'typeof Moderation' is not assignable to parameter of type 'Mismatch<"SlashRoute does not match the SlashHandler generic", "ban", "ban" | "kick">'. Types of construct signatures are incompatible. Type 'new (event: ChatInputCommandInteraction<"cached">, core: Core, dispatch: DispatchContext<DispatchKind>, sender: ReplySender) => Moderation' is not assignable to type 'new (...arguments_: any[]) => ["SlashRoute does not match the SlashHandler generic", { decorator: "ban"; generic: "ban" | "kick"; }]'. Type 'Moderation' is not assignable to type '["SlashRoute does not match the SlashHandler generic", { decorator: "ban"; generic: "ban" | "kick"; }]'.
class Moderation extends SlashHandler<'ban' | 'kick'> { public async execute(): Promise<void> {} }

Every route needs a case

Your editor lists the routes still waiting for one.

await this.match({ '
  • ban
  • kick

Leaving one out is a compile error.

@SlashRoute('ban', 'kick')
class Moderation extends SlashHandler<'ban' | 'kick'> {
    public async execute(): Promise<void> {
        await this.match({
Argument of type '{ ban: () => Promise<void>; }' is not assignable to parameter of type 'OnlyCases<SlashMatchCases<"ban" | "kick", "cached", never>, SlashMatchCases<"ban" | "kick", "cached", never>>'. Property 'kick' is missing in type '{ ban: () => Promise<void>; }' but required in type 'SlashMatchCases<"ban" | "kick", "cached", never>'.
ban: async () => { await this.reply('Banned.'); } }); } }

Use what the cases return

The code after match often needs a value that each case worked out. If you assign that value to a let above match, TypeScript reports the let as used before it's assigned, because it doesn't follow assignments inside the callbacks.

Return the value from each case. match resolves to what the case returned.

const outcome = await this.match({
const outcome:
    | {
          banned: boolean;
      }
    | {
          notified: boolean;
      }
ban: () => ({ banned: true }), kick: async () => ({ notified: true }) });

outcome is a union of both shapes, because each case returned its own. kick returns a promise, and match waits for it before it resolves.

Make every case return the same type

A union accepts whatever each case returns, so TypeScript only reports a wrong return at the code that reads the result. To get the error on the case itself, pass the type that every case must return.

@SlashRoute('ban', 'kick')
class Moderation extends SlashHandler<'ban' | 'kick'> {
    public async execute(): Promise<void> {
        const summary = await this.match<string>({
            ban: () => 'Banned.',
            kick: () => 1
Type 'number' is not assignable to type 'Promisable<string>'.
}); await this.reply(summary); } }

TypeScript reports the error on kick, which returns a number. summary is a string, the type you passed.

Write the cases inline when you pass a type. If you pass a map stored in a variable, TypeScript doesn't reject an extra key, so that key compiles and never runs.