You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

discord.js:CommandInteractionOptionResolver不存在getNumber方法问题

Discord.js 加法斜杠命令常见问题解决

一、getNumber方法不存在的原因及解决

getNumber是discord.js为数字类型选项提供的快捷获取方法,不存在的情况通常是以下原因:

  • 版本过低:该方法在discord.js v13及以上版本才支持,运行npm list discord.js查看当前版本,若版本低于v13,执行npm install discord.js@latest升级到最新稳定版。
  • 类型提示未加载:确保项目正确引入了discord.js的类型定义(discord.js自带类型,无需额外安装@types/discord.js),若使用TypeScript,检查tsconfig.json配置是否正常。

二、get方法的类型提示报错解决

使用options.get('num2')时,TypeScript无法推断选项的具体类型,会将value标注为string | number | boolean,导致编译时出现“无法将联合类型相加”的报错(尽管运行时value实际是数字)。有两种解决方式:

方式1:使用getNumber(推荐)

解决版本问题后,getNumber会直接返回纯数字类型的值,无需访问.value属性:

client.on('interactionCreate', async (interaction) => {
    if (!interaction.isCommand()) return;
    const { commandName, options } = interaction;

    if (commandName === 'add') {
        const num1 = options.getNumber('num1')!;
        const num2 = options.getNumber('num2')!;
        const sum = num1 + num2;

        interaction.reply({ content: `The sum is ${sum}` });
    }
});

注意:你之前的代码里写num1.value会报错,因为getNumber返回的直接是数字,不是带value属性的对象,这是对方法返回值的误解。

方式2:类型断言(临时解决)

如果暂时无法升级版本,可通过类型断言明确指定value的类型:

client.on('interactionCreate', async (interaction) => {
    if (!interaction.isCommand()) return;
    const { commandName, options } = interaction;

    if (commandName === 'add') {
        const num1Option = options.get('num1')!;
        const num2Option = options.get('num2')!;
        const num1 = num1Option.value as number;
        const num2 = num2Option.value as number;
        const sum = num1 + num2;

        interaction.reply({ content: `The sum is ${sum}` });
    }
});

三、额外注意点

  • 注册命令时你设置的type: DiscordJS.ApplicationCommandOptionType.Number是正确的,这保证了用户输入的是数字类型。
  • 使用非空断言!时,要确保选项已设置required: true,避免出现undefined的情况。

内容的提问来源于stack exchange,提问作者Jag

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 08:15:29