不和谐.js指南 : 打字稿中的类型 'Client<boolean>' 上不存在属性'commands'



node:v16.11.0"discord.js": "^13.2.0"

我正在设置一个例子Discord.js bot.

在本指南中,我要添加这一行:

client.commands = new Collection();

Typescript然后抱怨:Property 'commands' does not exist on type 'Client<boolean>'

这个答案似乎和我想要的是一样的。然而,我仍然遇到了一些问题。如果我添加一个declare module "discord.js"并宣布新类型,它似乎没有扩展现有类型,它覆盖。当我做的时候,它不知道什么是Collection定制输入文件,因为这是自定义新Discord.js图书馆。我不禁觉得这不该出现在官方指南中。

我想知道是否有人制作了一个typescript Discord bot,并找到了解决这个问题的新方法。

感谢您的宝贵时间。

- edit -

所以我有机会在搜索中找到我自己的问题,发现我最初回答错了。事实证明,我们在遵循Discord.js指南时得到此错误的原因是因为在客户端类上根本没有commands属性。它只是指南使用的一个模式,Typescript会调用它。

一旦我为我的项目正确设置了Typescript,添加命令将表示Collection<any, any>工作得很好。

src/@types/discord.d.ts

import { Collection } from "discord.js";
declare module "discord.js" {
export interface Client {
commands: Collection<any, any>;
}
}

tsconfig.json

{
"compilerOptions": {
"typeRoots": ["src/@types", "node_modules/@types"],
"outDir": "dist"
},
"include": ["src"],
"exclude": ["node_modules"],
"extends": "@tsconfig/node18/tsconfig.json"
}

孩子的答案——

好吧。所以我想明白了。

创建types/common/discord.d.ts

不要像我做的那样,只包括这个:

declare module "discord.js" {
export interface Client {
commands: Collection<unknown, any>
}
}

确保这是在顶部

import { Collection } from "discord.js";

那么它实际上会扩展现有的定义,并为定义引入Collection,而不是替换它。

此解决方案还需要将"@typescript-eslint/no-explicit-any": "off"添加到es-lint中,这要归功于Collection扩展了Map并接受任何值。

你有两种选择,一种是难的,一种是容易的,难的是:

declare module "discord.js" {
export interface Client {
commands: Collection<unknown, any>
}
}

简单的方法是扩展discord类,大家都这么做:

// utils/Client.ts
import { Client, Collection } from "discord.js"
export default class MyClient extends Client {
collection: Collection<any, any> // use correct type :)
constructor(options) {
super(options)
this.collection = new Collection();
this.loadCommands()
}
loadCommands() {
// enter code here
}
}

我知道已经有答案了,但是对于那些不想导入东西的人,请这样做:

module "discord.js" {
export interface Client {
foo: number;
}
}
export {}

在他们的文档中提到。建议扩展基本客户机并对其进行类型转换以添加命令属性。您可以创建一个新的接口,如下所示:

interface ClientWithCommands extends Client {
commands: Collection<string, any>
}

一旦定义了接口,就可以使用"as"继续对Client实例进行类型转换。关键字:

const client = new Client({
intents: [
GatewayIntentBits.Guilds,
],
}) as ClientWithCommands

现在,您可以继续添加如下命令:

client.commands = new Collection()
...

相关内容