Search code examples
node.jstypescriptmongodbmongoose

TypeScript: All declarations of 'Query' must have identical type parameters


I get "All declarations of 'Query' must have identical type parameters." error when I hover over "Query" in interface section.

import mongoose from "mongoose";
import * as redis from "redis";

declare module "mongoose" {
    interface Query {
        cache():this;
        useCache:boolean;
    }
};

const client = redis.createClient({ url: process.env.REDIS });

client.on("connect", () => console.log("Redis Connection Is Successful!"));
client.on("err", (err) => console.log("Redis Client Error:", err));
client.connect();

//Hooking into mongoose's query generation and execution process
//in order to make the caching reusable in the codebase
const exec = mongoose.Query.prototype.exec;

mongoose.Query.prototype.cache = function() {
    this.useCache = true;
    return this;
}

Solution

  • Query is initially declared with some generic type parameters in mongoose. TypeScript is just asking you to honor those type parameters in your augmentation:

    declare module "mongoose" {
        interface Query<ResultType, DocType, THelpers = {}, RawDocType = DocType> {
            cache(): this;
            useCache: boolean;
        }
    }
    

    You can easily do it by hovering over Query and copy pasting the parameters shown:

    enter image description here

    Playground