Mongoose getter函数触发TS2590类型过复杂错误求助
解决TS2590: Expression produces a union type that is too complex to represent错误(Mongoose + TypeScript)
这个错误源于Mongoose在推导包含自定义类型(UserId)的Schema字段getter时,生成了TypeScript无法处理的复杂联合类型。以下是几种可行的解决方案:
方案一:显式指定Schema的类型参数
通过明确Schema的第三个类型参数(用于定义getter/setter的类型),帮助TypeScript简化类型推导,避免生成过于复杂的联合类型。
修改后的Schema定义:
const schema = new Schema<User, {}, { id: typeof idFromString }>({ id: { type: String, required: true, unique: true, set: idToString, get: idFromString }, email: { type: String, required: true, unique: true, set: toLowercase }, password: { type: String, required: true }, status: { type: Number, required: true, default: 0 }, code: { type: String }, accountCreationDate: { type: Date, required: true, default: new Date() } });
方案二:给getter添加类型断言
通过类型断言让TypeScript明确getter的返回类型,减少自动推导的复杂度:
方式1:在get选项中直接断言
id: { type: String, required: true, unique: true, set: idToString, get: (value: string) => idFromString(value) as UserId },
方式2:在getter函数内部断言
function idFromString(value: string): UserId { return new UserId(value) as UserId }
方案三:绕过Mongoose getter,手动转换类型
移除Schema中的getter,在查询数据后手动将字符串id转换为UserId类型,适合不依赖Mongoose自动转换的场景:
- 移除Schema里的
get: idFromString配置 - 查询时手动转换:
// 示例查询 const userDoc = await UserModel.findOne({ email: 'example@test.com' }).lean(); if (userDoc) { const user = new User( new UserId(userDoc.id), userDoc.email, userDoc.password, userDoc.status, userDoc.code, userDoc.accountCreationDate ); }
方案四:升级Mongoose版本
部分Mongoose版本在类型推导逻辑上存在bug,尝试升级到8.x系列的最新稳定版或9.x版本,可能已修复该类型复杂度问题。
内容的提问来源于stack exchange,提问作者Igor Drljić
相关产品推荐
相关产品推荐

