Assign custom methods in mongoose .d.ts so I can use them anywhere with mongoose in typescript
Your augmentation does work. It needs to be placed somewhere that you have configured TypeScript to look for source files. The declare module
style of type definition is called an "ambient declaration" which means that you don't have to put it in any particular directory or file. It can even be in a regular .ts
file. The easiest thing to do is to put the declaration in cache.ts
, the same file where you assign mongoose.Query.prototype.cache
.
Edit: I forgot to address your specific question about augmenting a class. As you guessed you can augment a class by using the interface
keyword. That is because in TypeScript defining a class does two things: it defines a value (the constructor function that is invoked when you call, e.g., new DocumentQuery
), and a type for instances of the class which is really an interface. The value and the type both have the same name. Because the type part of a class is an interface you can augment it like any other interface.
So in this case you augment the DocumentQuery
type, which is the superclass of Query
, but you assign the cache
method to the Query
prototype. That works because Query
extends DocumentQuery
, so when you declare that DocumentQuery
now has a cache
method TypeScript assumes that subclasses, including Query
, have the same method. This does lead to a discrepancy: TypeScript now assumes that DocumentQuery
instances have a cache
method, but you only really defined that method for Query
. It would be more accurate to either change your type declaration to augment Query
instead of DocumentQuery
, or to assign the method implementation to DocumentQuery.prototype
instead of to Query.prototype
.