简体   繁体   English

Node.js 和 Typescript,如何动态访问导入的模块

[英]Node.js and Typescript, how to dynamically access imported modules

I am working on creating a discord bot in TypeScript.我正在努力在 TypeScript 中创建一个 discord 机器人。 I wanted to create a generic command disbatcher and here is my work so far:我想创建一个通用的命令分派器,这是我到目前为止的工作:

app.ts:应用程序.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命令/索引.ts

export {default as ping} from './ping';
export {default as prong} from './prong';

Ping.ts : same structure for all commands Ping.ts :所有命令的结构相同

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:索引命令导入时,我可以使用以下命令成功调用正确的执行 function:

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?无论如何我可以将命令导入类型转换为某种 object 或集合吗? 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.我是 typescript 的新手,我很好奇有什么可能。

I suggest a different approach for your commands, this approach fixes 2 things:我为您的命令建议一种不同的方法,这种方法修复了两件事:

  • You don't forget to export files properly不要忘记正确导出文件
  • You get type safe commands你得到类型安全的命令

Let's first create a interface for your commands, this interface describes the metadata, add as many as you want让我们首先为你的命令创建一个接口,这个接口描述元数据,你想添加多少就添加多少

export interface Command {
  name: string
  description: string
  // Making `args` optional
  execute(message: Message, args?: string[]) => any
}

Now that you have a shape for your command, let's make sure all your commands have the right shape现在您已经为命令设置了形状,让我们确保您的所有命令都具有正确的形状

import { Command } from "./types"

// This will complain if you don't provide the right types for each property
const command: Command = {
  name: "ping",
  description: "Ping!",
  execute(message: Message, args: string[]) => {
    message.channel.send("Pong")
  }
}

export = command

The next part is loading your commands, discord.js has glob as a dependency which can help you read files in a directory easily, let's use some utilities so we can have nice async / await usage下一部分是加载您的命令,discord.js 具有glob作为依赖项,它可以帮助您轻松读取目录中的文件,让我们使用一些实用程序,这样我们就可以很好地使用 async / await

import glob from "glob" // included by discord.js
import { promisify } from "util" // Included by default
import { Command } from "./types"

// Make `glob` return a promise
const globPromise = promisify(glob)

const commands: Command = []

client.once("ready", async () => {
  // Load all JavaScript / TypeScript files so it works properly after compiling
  // Replace `test` with "await globPromise(`${__dirname}/commands/*.{.js,.ts}`)"
  // I just did this to fix SO's syntax highlighting!
  const commandFiles = test

  for (const file of commandFiles) {
    // I am not sure if this works, you could go for require(file) as well
    const command = await import(file) as Command
    commands.push(command)
  }
})

const prefix = "!"

client.on("message", message => {
  // Prevent the bot from replying to itself or other bots
  if (message.author.bot) {
    return
  }

  const [commandName, ...args] = message.content
    .slice(prefix.length)
    .split(/ +/)

  const command = commands.find(c => c.name === commandName)

  if (command) {
    command.execute(message, args)
  }
})

I hope this gives you some good starting point and shows you the power of TypeScript我希望这能给你一个好的起点,并向你展示 TypeScript 的力量

You could import the type and then cast it like this您可以导入类型,然后像这样进行转换

commands[command as Type].execute();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM