I am working on creating a discord bot in TypeScript. I wanted to create a generic command disbatcher and here is my work so far:
app.ts:
import * as Discord from 'discord.js';
import * as config from '../config'
import * as commands from './Commands/index'
const token : string = config.Token;
const _client = new Discord.Client();
_client.on('message', (msg) => {
let args : Array<string> = msg.content.split(' ')
let command : string = args.shift() || " ";
if(!command.startsWith("!")) return;
else{
commands[`${command.toLower().substring(1)}`]
}
})
Commands/Index.ts
export {default as ping} from './ping';
export {default as prong} from './prong';
Ping.ts : same structure for all commands
import { Message } from "discord.js";
export default {
name : 'ping',
description: 'Ping!',
execute(message: Message, args: Array<string>){
message.channel.send('Pong.');
}
}
When indexing the commands import I can successfuly call the right execute function using this:
commands['pong'].execute()
however, when trying to dynamically index it like this:
commands[command].execute()
I recieve the following error:
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'typeof import("c:/Users/alexs/Desktop/Discord Bot/src/Commands/index")'. No index signature with a parameter of type 'string' was found on type 'typeof import("c:/Users/alexs/Desktop/Discord Bot/src/Commands/index")'
Is there anyway I can typecast the command import as some kind of object or collection? If not, is there a way I could create some kind of accssesor to make this work? I am newer to typescript and am curious what is possible.
commands[command].execute()? Where doescommandvariable come from?