为了账号安全,请及时绑定邮箱和手机立即绑定

坚持将变量添加到 Discord Client 对象 Typescript

坚持将变量添加到 Discord Client 对象 Typescript

慕容708150 2022-11-11 16:55:57
我是 Typescript 的新手,并使用 Typescript 编写了一个 Discord 机器人。我想向客户端对象添加一个变量“命令”。例如在 Javascript 中,你使用这个:Javascriptconst { Client } = require('discord.js');const client = new Client();client.commands = 'commands';console.log(client.commands);// 'commands'但现在我想添加类似于 Typescript 的内容。但是当我在 Typescript 中使用它时,出现以下错误:Property 'commands' does not exist on type 'Client'.ts(2339)我该如何解决这个问题?我目前的代码:export class HalloClient {    private client: Client;     constructor() {        this.client = new Client();        this.client.commands = new Collection();    }    public start(): void {        console.log(`- Client | Starting process...`);        new RegisterEvents('../events/', this.client).load();        new MongoConnection(process.env.mongouri).createConnection();         console.log(this.client);        this.client.login(process.env.token);    }}
查看完整描述

1 回答

?
白板的微信

TA贡献1883条经验 获得超3个赞

我在使用打字稿并遵循https://discordjs.guide的指南时遇到了同样的问题


默认情况下,commands它不是对象的现有属性类型,但您可以通过创建文件Discord.Client轻松地使用您自己的类型扩展 Discord.js 类型。.d.ts


discord.d.ts我的项目目录中有文件,它包含:


declare module "discord.js" {

    export interface Client {

        commands: Collection<unknown, any>

    }

}

这解决了我的问题。


如果您使用discord.js 指南中的单文件样式命令,甚至更好:


import { Message } 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[]) => SomeType // Can be `Promise<SomeType>` if using async

    }

}

这样,您还可以在从 访问命令对象时获得代码补全,如果需要this.client.commands.get("commandName"),您还可以从.Commandimport { Command } from "discord.js"


当我想从命令文件中严格键入导出的命令时,我发现这很有用,例如:


import { Command } from "discord.js";


// Now `command` is strictly typed to `Command` interface

const command: Command = {

    name: "someCommand",

    description: "Some Command",

    execute(message, args): SomeType /* Can be Promise<SomeType> if using async */ {

        // do something

    }

};


export = command;


查看完整回答
反对 回复 2022-11-11
  • 1 回答
  • 0 关注
  • 94 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号