亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

堅持將變量添加到 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 關注
  • 93 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號