猿问

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

我是 Typescript 的新手,并使用 Typescript 编写了一个 Discord 机器人。我想向客户端对象添加一个变量“命令”。例如在 Javascript 中,你使用这个:


Javascript


const { 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);

    }


}


慕容708150
浏览 95回答 1
1回答

白板的微信

我在使用打字稿并遵循https://discordjs.guide的指南时遇到了同样的问题默认情况下,commands它不是对象的现有属性类型,但您可以通过创建文件Discord.Client轻松地使用您自己的类型扩展 Discord.js 类型。.d.tsdiscord.d.ts我的项目目录中有文件,它包含:declare module "discord.js" {&nbsp; &nbsp; export interface Client {&nbsp; &nbsp; &nbsp; &nbsp; commands: Collection<unknown, any>&nbsp; &nbsp; }}这解决了我的问题。如果您使用discord.js 指南中的单文件样式命令,甚至更好:import { Message } from "discord.js";declare module "discord.js" {&nbsp; &nbsp; export interface Client {&nbsp; &nbsp; &nbsp; &nbsp; commands: Collection<unknown, Command>&nbsp; &nbsp; }&nbsp; &nbsp; export interface Command {&nbsp; &nbsp; &nbsp; &nbsp; name: string,&nbsp; &nbsp; &nbsp; &nbsp; description: string,&nbsp; &nbsp; &nbsp; &nbsp; execute: (message: Message, args: string[]) => SomeType // Can be `Promise<SomeType>` if using async&nbsp; &nbsp; }}这样,您还可以在从 访问命令对象时获得代码补全,如果需要this.client.commands.get("commandName"),您还可以从.Commandimport { Command } from "discord.js"当我想从命令文件中严格键入导出的命令时,我发现这很有用,例如:import { Command } from "discord.js";// Now `command` is strictly typed to `Command` interfaceconst command: Command = {&nbsp; &nbsp; name: "someCommand",&nbsp; &nbsp; description: "Some Command",&nbsp; &nbsp; execute(message, args): SomeType /* Can be Promise<SomeType> if using async */ {&nbsp; &nbsp; &nbsp; &nbsp; // do something&nbsp; &nbsp; }};export = command;
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答