Discord.js v13.2.0 + TypeScript 中 Client<boolean> 不存在 'commands' 属性的解决方案求助
解决Discord.js v13 + TypeScript中Client.commands的类型错误问题
我之前开发Discord机器人时也碰到过完全一样的问题——把官方指南里的JS代码直接搬到TS里,就会报Property 'commands' does not exist on type 'Client<boolean>',而且扩展类型时还容易踩覆盖原有定义的坑。下面是我摸索出来的靠谱解决方案:
1. 正确扩展Discord.js的Client类型(避免覆盖原有定义)
不要直接空写declare module "discord.js",这会覆盖整个库的类型。正确的做法是先导入Discord.js的核心类型,再扩展Client接口:
首先创建一个类型声明文件,比如src/types/discord.d.ts,写入以下内容:
// 先导入需要用到的Discord.js类型,确保TS能识别原有模块 import { Collection } from 'discord.js'; // 先定义你的Command类型(根据自己的命令结构调整) export interface Command { name: string; description: string; // 示例:如果用斜杠命令,这里是CommandInteraction;前缀命令可以是Message execute: (interaction: import('discord.js').CommandInteraction) => Promise<void>; } // 扩展Discord.js的Client接口 declare module 'discord.js' { interface Client { // 给Client添加commands属性,类型是Collection<string, Command> commands: Collection<string, Command>; } }
2. 让TypeScript识别你的自定义类型
打开tsconfig.json,确保include数组包含你的类型文件路径,比如:
{ "include": [ "src/**/*.ts", "src/types/**/*.d.ts" // 加上这行,让TS加载自定义类型 ] }
3. 初始化Client.commands属性
现在你可以正常给Client实例添加commands属性了,不会再报类型错误:
import { Client, Collection, Intents } from 'discord.js'; import { Command } from './types/discord'; const client = new Client({ intents: [Intents.FLAGS.GUILDS] }); // 初始化commands集合 client.commands = new Collection<string, Command>(); // 后续可以正常添加命令,比如: // client.commands.set('ping', { // name: 'ping', // description: 'Ping the bot', // execute: async (interaction) => { // await interaction.reply('Pong!'); // } // });
为什么之前的方法会失败?
当你直接写declare module "discord.js"而没有先导入原有类型时,TypeScript会认为你要重新定义整个模块的类型,而不是扩展它。通过先导入Collection和其他需要的类型,TS会把你的扩展和原有模块的类型合并,而不是覆盖。
官方指南主要面向JavaScript开发者,所以没有提到TypeScript下的类型扩展细节,这是TS适配第三方库时的常见问题,按照上面的步骤就能完美解决啦。
内容的提问来源于stack exchange,提问作者devleo
相关产品推荐
相关产品推荐

