Mongoose扩展Query接口时出现TypeScript类型参数不一致错误
Mongoose扩展Query接口时出现TypeScript类型参数不一致错误
嘿,这个问题我之前踩过坑!你遇到的All declarations of 'Query' must have identical type parameters错误,本质是因为Mongoose的Query接口本身是泛型接口,你直接声明interface Query没有匹配它原本的泛型参数,导致TypeScript认为你定义了一个和原接口不兼容的新声明。
问题根源
Mongoose官方的Query接口定义是带泛型参数的,大概结构是这样的:
interface Query<ResultType = Document, DocType extends Document = Document, THelpers = {}> { // 原有方法和属性 }
你扩展的时候必须完整继承这些泛型参数,否则就会和原接口的类型声明冲突,触发类型参数不一致的报错。
修复方案
修改你在declare module "mongoose"里的Query接口声明,加上对应的泛型参数,同时确保扩展的方法和属性能正确适配泛型逻辑:
import mongoose from "mongoose"; import * as redis from "redis"; declare module "mongoose" { // 匹配原Query接口的泛型参数结构 interface Query<ResultType = Document, DocType extends Document = Document, THelpers = {}> { cache(): this; useCache: boolean; } }; const client = redis.createClient({ url: process.env.REDIS }); client.on("connect", () => console.log("Redis Connection Is Successful!")); client.on("error", (err) => console.log("Redis Client Error:", err)); // 修正:Redis错误事件名称是"error"而非"err" client.connect(); // 缓存逻辑的原型扩展保持不变 const exec = mongoose.Query.prototype.exec; mongoose.Query.prototype.cache = function() { this.useCache = true; return this; }
额外小提示
我顺便帮你修正了Redis事件监听的小问题:错误事件的名称是error而不是err,不修正的话Redis的错误没法被正确捕获到哦~
这样修改后,TypeScript就会识别到你是在扩展原有泛型接口,而不是重新定义一个新接口,类型参数不一致的错误就会消失啦。
备注:内容来源于stack exchange,提问作者semih
相关产品推荐
相关产品推荐

