diff --git a/test/types/models.test.ts b/test/types/models.test.ts index 22b0916941..0cd4b08c1e 100644 --- a/test/types/models.test.ts +++ b/test/types/models.test.ts @@ -1056,3 +1056,31 @@ async function gh16526() { const insertManyResult = await Tank.insertMany([{ name: 'test' }], { lean: true, rawResult: true }); expectType(insertManyResult.insertedCount); } + +async function gh15693() { + interface IUser { + name: string; + } + + interface UserMethods { + printName(this: IUser): void; + getName(): string; + } + + const schema = new Schema, UserMethods>({ name: { type: String, required: true } }); + schema.method('printName', function printName(this: IUser) { + expectError(this.isModified('name')); + expectError(this.doesNotExist()); + expectType(this.name); + console.log(this.name); + }); + schema.method('getName', function getName() { + expectType(this.isModified('name')); + return this.name; + }); + const User = model('user', schema); + + const leanInst = await User.findOne({}).lean().orFail(); + User.schema.methods.printName.apply(leanInst); + +} diff --git a/types/models.d.ts b/types/models.d.ts index afadaff43e..b2ad98c627 100644 --- a/types/models.d.ts +++ b/types/models.d.ts @@ -1081,7 +1081,7 @@ declare module 'mongoose' { recompileSchema(): void; /** Schema the model uses. */ - schema: Schema; + schema: TSchema; /** Creates a `updateMany` query: updates all documents that match `filter` with `update`. */ updateMany( diff --git a/types/utility.d.ts b/types/utility.d.ts index 44d5ac1b0c..4c53706541 100644 --- a/types/utility.d.ts +++ b/types/utility.d.ts @@ -2,7 +2,7 @@ declare module 'mongoose' { type IfAny = 0 extends 1 & IFTYPE ? THENTYPE : ELSETYPE; - type IfUnknown = unknown extends IFTYPE ? THENTYPE : IFTYPE; + type IsUnknown = unknown extends T ? true : false; type WithLevel1NestedPaths = { [P in K | NestedPaths, K>]: P extends K @@ -135,7 +135,7 @@ declare module 'mongoose' { */ type AddThisParameter = { [K in keyof T]: T[K] extends (...args: infer A) => infer R - ? ThisParameter extends unknown + ? IsUnknown> extends true ? (this: D, ...args: A) => R : T[K] : T[K];