我查看了TypeScript的文档,以及关于扩展第三方模块的多个指南,但这些方法都不起作用。
我试图完成的是向discord.Collection((.类型的discord客户端添加一个commands属性
如果我这样做:
// discord.d.ts file
import * as Discord 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[]) => any; // Can be `Promise<SomeType>` if using async
}
}
// some other file
import * as Discord from "discord.js";
import "discord.d.ts";
const client = new Discord.Client();
client.commands = new Discord.Collection(); // ERROR Property 'commands' does not exist on type 'Client'.ts(2339)
我找到的唯一解决方案是将Discord.Client((和Discord.Collection封装在一个单独的类中,然后以这种方式访问它们,或者在node_modules中的Discord.js index.d.ts文件中添加一个类型声明(这意味着克隆项目的其他人都无法访问该类型,因为node_module在gitignore中(。是我遗漏了什么,还是这个库不支持我尝试的声明扩展?
谢谢!
实现您想要做的事情的最简单和常见的方法是创建另一个扩展Discord.js的类:
class MySuperClient extends Discord.Client {
public commands: Discord.Collection<string, Command>;
constructor(){
super();
this.commands = new Discord.Collection();
}
}
const client = new MySuperClient()
client.login('token');
client.on('ready', () => console.log('Ready! Loaded '+client.commands.size+' commands!');