【问题标题】:Unable to use module changes from typescript declaration file无法使用打字稿声明文件中的模块更改
【发布时间】:2021-11-04 12:36:35
【问题描述】:

src/index.d.ts:



    declare module "discord.js" {
        export interface Client {
            commands: import('discord.js').Collection<unknown, Command>,
            handleEvents(eventFiles: string[], path: string): any,
            handleCommands(eventFiles: string[], path: string): any,
            commandArray: any
        }

        export interface Command {
            name: string,
            description: string,
            execute: (message: import('discord.js').Message, args?: string[]) => Promise<Command> // Can be `Promise<SomeType>` if using async
        }
    }

    export {}

每当我使用它时,当我使用.handleCommands.handleEvents 时,我会得到:

“typeof Client”类型上不存在属性“handleCommands”

我在这里尝试使用它src/index.ts

import DiscordJS, { Intents, Collection, Client } from 'discord.js'
import fs from 'fs'
require('dotenv').config();

export const client: Client = new DiscordJS.Client({ intents: [Intents.FLAGS.GUILDS] });
client.commands = new Collection();

const functions = fs.readdirSync('./src/functions').filter((file: string) => file.endsWith('.ts'));
const eventFiles = fs.readdirSync('./src/events').filter((file: string) => file.endsWith('.ts'));
const commandFolders = fs.readdirSync('./src/commands').filter((file: string) => file.endsWith('.ts'));

(async () => {
    for (const  file of functions) {
        require(`./functions/${file}`)(client);
    }
    client.handleEvents(eventFiles, './src/events');
    client.handleCommands(commandFolders, './src/commands');
    client.login(process.env.TOKEN);
})

请帮助我,我不知道我还能做什么。

【问题讨论】:

  • 出于好奇 Client#commands 有效吗?
  • CLient#commands in import?

标签: typescript discord.js


【解决方案1】:

您已经正确使用了声明文件,但是它只提供了命令的类型,而不是实际的要执行的代码 - 你必须自己提供:

client.handleEvents = (eventFiles, path) => { /* ... */ }
client.handleCommands = (eventFiles, path) => { /* ... */ }

编辑:我还注意到您输入Client#commandsCommand#execute 的方式是错误的; ESM import() 函数返回一个承诺,一个你没有解决的承诺。一个更简单的解决方案是在文件顶部静态导入它们,如下所示:

import { Collection, Message } from "discord.js";

declare module "discord.js" {
  export interface Client {
    commands: Collection<unknown, Command>
    // ...
  }
  export interface Command {
    // ...
    execute: (message: Message, args?: string[]) => Promise<Command>
  }
}

另外,我不认为文件末尾的export {} 是必需的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-20
    • 2017-02-16
    • 1970-01-01
    • 2018-11-06
    • 2020-11-27
    • 2017-10-18
    相关资源
    最近更新 更多