Zamurph
Zamurph

Reputation: 89

Discord.js type/declartion extension not working

I've looked over TypeScript's docs, as well as multiple guides around extending third-party modules and none of the methods are working.

What I'm trying to accomplish is adding a commands property to the discord client that has a type of Discord.Collection().

If I do this:


// discord.d.ts file
import * as Discord from "discord.js";

declare module "discord.js" {
    export interface Client {
        commands: Collection<unknown, Command>;
    }

    export interface Command {
        name: string;
        description: string;
        execute: (message: Message, args: string[]) => any; // Can be `Promise<SomeType>` if using async
    }
}


// some other file

import * as Discord from "discord.js";
import "discord.d.ts";

const client = new Discord.Client();
client.commands = new Discord.Collection(); // ERROR Property 'commands' does not exist on type 'Client'.ts(2339)

The only solutions I've found are either wrapping the Discord.Client() and Discord.Collection in a separate class and then accessing them that way, or adding a type declaration to the discord.js index.d.ts file within node_modules (which means that no one else who clones the project would have access to that type because node_modules is in the gitignore). Am I missing something or does this library just not support declaration extension in the way that I'm attempting it?

Thanks!

Upvotes: 1

Views: 1858

Answers (1)

Androz2091
Androz2091

Reputation: 3005

The simplest and common way to achieve what you'd like to do is creating another class that extends the Discord.js one:

class MySuperClient extends Discord.Client {

     public commands: Discord.Collection<string, Command>;

     constructor(){
          super();
          this.commands = new Discord.Collection();
     }

}

const client = new MySuperClient()
client.login('token');
client.on('ready', () => console.log('Ready! Loaded '+client.commands.size+' commands!');

Upvotes: 2

Related Questions