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

TypeScript 'never'类型问题:无法访问duplicacyCheck.name属性

解决TypeScript报错“Property 'name' does not exist on type 'never'”

这个问题通常是Mongoose的类型推断未正确关联到你的userDoc接口导致的,以下是几种可行的解决方法:

方法1:确保Model正确关联类型

创建User Model时,明确指定泛型类型为userDoc,让Mongoose能正确推断findOne的返回类型:

// 先定义Schema结构
const userSchema = new mongoose.Schema({
  name: { type: String, required: true },
  userId: { type: String, required: true },
  createdAt: String,
  updatedAt: String,
  version: Number,
  createdBy: String,
  updatedBy: String
});

// 关键步骤:指定泛型<userDoc>绑定接口
const User = mongoose.model<userDoc>('User', userSchema);

// 后续调用findOne时,返回类型会自动识别为userDoc | null
const duplicacyCheck = await User.findOne({
  name: name,
  userId: id,
});

if (duplicacyCheck) {
  console.info(duplicacyCheck.name, "duplicacyCheck"); // 不再报错
}

方法2:手动类型断言

如果暂时无法调整Model定义,可以在findOne调用后手动断言类型:

const duplicacyCheck = await user.findOne({
  name: name,
  userId: id,
}) as userDoc | null;

if (duplicacyCheck) {
  console.info(duplicacyCheck.name, "duplicacyCheck");
}

方法3:升级Mongoose版本

部分旧版本Mongoose在TypeScript类型推断上存在bug,升级到最新稳定版(如v7及以上)可能自动解决该问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 03:52:08