Discord JS v14(TypeScript)添加按钮至interaction.reply时类型报错
Discord.js v14 + TypeScript:Interaction回复添加按钮的类型错误修复
问题原因
在Discord.js v14中,ActionRowBuilder默认泛型为AnyComponentBuilder,TypeScript无法自动推导其符合InteractionReplyOptions的components类型约束,导致提示缺少type属性的类型错误。
解决方案
以下三种方法均可解决该问题:
方法1:明确指定ActionRowBuilder的泛型类型
给ActionRowBuilder指定具体的组件类型(这里是ButtonBuilder),让TypeScript正确识别类型:
import { ActionRowBuilder, ButtonBuilder, ButtonStyle } from 'discord.js'; // ... return interaction.reply({ content: `There was an error while running the channel command. Please try again later. (${error})`, ephemeral: true, components: [new ActionRowBuilder<ButtonBuilder>({ components: [ new ButtonBuilder({ customId: '1', label: 'yes', style: ButtonStyle.Success }) ] })] });
方法2:使用链式调用构建组件
通过.addComponents()方法替代构造函数传参,TypeScript会自动推导正确的类型:
import { ActionRowBuilder, ButtonBuilder, ButtonStyle } from 'discord.js'; // ... const errorActionRow = new ActionRowBuilder<ButtonBuilder>() .addComponents( new ButtonBuilder() .setCustomId('1') .setLabel('yes') .setStyle(ButtonStyle.Success) ); return interaction.reply({ content: `There was an error while running the channel command. Please try again later. (${error})`, ephemeral: true, components: [errorActionRow] });
方法3:将Builder转换为JSON格式
调用.toJSON()方法将ActionRowBuilder实例转换为Discord API接受的原始数据结构,绕过类型推导问题:
import { ActionRowBuilder, ButtonBuilder, ButtonStyle } from 'discord.js'; // ... return interaction.reply({ content: `There was an error while running the channel command. Please try again later. (${error})`, ephemeral: true, components: [new ActionRowBuilder({ components: [ new ButtonBuilder({ customId: '1', label: 'yes', style: ButtonStyle.Success }) ] }).toJSON()] });
注意事项
确保已正确导入Discord.js提供的所有相关类和枚举,避免因导入不全导致的额外类型错误。
内容的提问来源于stack exchange,提问作者user18609597
相关产品推荐
相关产品推荐

