The this types of each signature are incompatible mongoose methods with Typescript

Viewed 556

I have created a model with mongoose and want to add a method. Lets assume I have these interfaces for the model (boilerplate):

interface TestAttrs { attr1: string }
interface TestModel extends mongoose.Model<TestDoc> { build(attrs: TestAttrs): TestDoc }
interface TestDoc extends TestAttrs, mongoose.Document { testMethod(): Promise<any> }

export const testSchema = new mongoose.Schema({ attr1: {type: String} })
testSchema.statics.build = (attrs: TestAttrs) => { return new Test(attrs) }

const Test = mongoose.model<TestDoc, TestModel>('Test', testSchema)

So now I want to add the testMethod() like this:

testSchema.methods.testMethod = async function(this: TestDoc): Promise<any> {
  console.log(this.attr1) // Do something with the attr1...
}

But now I get the error that the TestDoc type ist not assignable to the type of Document (from mongoose. Why is that? I mean the TestDoc extends the mongoose Document type, so wouldn't it be possible?

To give you the full error message:

error TS2322: Type '(this: TestDoc) => Promise<any>' is not assignable to type '(this: Document<any>, ...args: any[]) => any'.
The 'this' types of each signature are incompatible.
Type 'Document<any>' is missing the following properties from type 'TestDoc': testMethod, attr1

I mean of course the Document type is missing these properties, that's why I have the TestDoc. If I give the 'this' the any type, then it works like expected, but why is Typescript throwing an error here?

I've also tried to modify the TestDoc interface to TestDoc that extends from Document, and adding the args argument. Thanks in advance!

0 Answers
Related