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

TypeScript编译报错:user.id不存在(类型识别异常)

Discord.js messageReactionAdd事件user参数类型识别错误修复

在使用discord.js开发Discord机器人时,遇到TypeScript编译错误:messageReactionAdd事件回调的user参数本应为User | PartialUser类型(包含id属性),但编译器错误将其识别为MessageReaction | PartialMessageReaction,抛出TS2339错误提示id不存在。实际运行时打印user,结果是正确的User实例。

相关代码片段

client.on("messageReactionAdd", async (reaction, user) => {
  console.log(user.id)
})

编译错误信息

index.ts:38:20 - error TS2339: Property 'id' does not exist on type 'MessageReaction | PartialMessageReaction'.
  Property 'id' does not exist on type 'MessageReaction'.
38   console.log(user.id)

修复方案

  • 显式指定参数类型
    直接给回调参数添加正确的类型注解,强制TypeScript使用正确的类型定义:
import { MessageReaction, User, PartialUser } from 'discord.js';

client.on("messageReactionAdd", async (reaction: MessageReaction | PartialMessageReaction, user: User | PartialUser) => {
  console.log(user.id);
});
  • 确保依赖版本匹配
    若使用discord.js v14及以上版本,它自带类型定义,无需单独安装@types/discord.js;若使用v13及以下版本,需保证@types/discord.js版本与discord.js主包版本完全一致,避免类型定义不兼容。

  • 处理Partial对象(可选)
    如果user是PartialUser类型(仅包含部分数据的对象),可先调用fetch()获取完整用户数据,避免潜在的属性缺失问题:

client.on("messageReactionAdd", async (reaction, user) => {
  if (user.partial) await user.fetch();
  console.log(user.id);
});
  • 检查TypeScript配置
    确认tsconfig.json的strict模式未被错误配置,若存在自定义类型覆盖默认定义,可重置types配置项确保包含discord.js:
{
  "compilerOptions": {
    "types": ["discord.js"]
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 13:41:41