Skip to content

Commit 008d95d

Browse files
committed
types: correct Model.schema type and fix unknown check for this param type in schema.methods
Fix #15693
1 parent 753d975 commit 008d95d

File tree

3 files changed

+31
-2
lines changed

3 files changed

+31
-2
lines changed

test/types/models.test.ts

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1056,3 +1056,31 @@ async function gh16526() {
10561056
const insertManyResult = await Tank.insertMany([{ name: 'test' }], { lean: true, rawResult: true });
10571057
expectType<number>(insertManyResult.insertedCount);
10581058
}
1059+
1060+
async function gh15693() {
1061+
interface IUser {
1062+
name: string;
1063+
}
1064+
1065+
interface UserMethods {
1066+
printName(this: IUser): void;
1067+
getName(): string;
1068+
}
1069+
1070+
const schema = new Schema<IUser, Model<IUser>, UserMethods>({ name: { type: String, required: true } });
1071+
schema.method('printName', function printName(this: IUser) {
1072+
expectError(this.isModified('name'));
1073+
expectError(this.doesNotExist());
1074+
expectType<string>(this.name);
1075+
console.log(this.name);
1076+
});
1077+
schema.method('getName', function getName() {
1078+
expectType<boolean>(this.isModified('name'));
1079+
return this.name;
1080+
});
1081+
const User = model('user', schema);
1082+
1083+
const leanInst = await User.findOne({}).lean().orFail();
1084+
User.schema.methods.printName.apply(leanInst);
1085+
1086+
}

types/models.d.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1081,7 +1081,7 @@ declare module 'mongoose' {
10811081
recompileSchema(): void;
10821082

10831083
/** Schema the model uses. */
1084-
schema: Schema<TRawDocType>;
1084+
schema: TSchema;
10851085

10861086
/** Creates a `updateMany` query: updates all documents that match `filter` with `update`. */
10871087
updateMany<ResultDoc = THydratedDocumentType>(

types/utility.d.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ declare module 'mongoose' {
33
? THENTYPE
44
: ELSETYPE;
55
type IfUnknown<IFTYPE, THENTYPE> = unknown extends IFTYPE ? THENTYPE : IFTYPE;
6+
type IsUnknown<T> = unknown extends T ? true : false;
67

78
type WithLevel1NestedPaths<T, K extends keyof T = keyof T> = {
89
[P in K | NestedPaths<Required<T>, K>]: P extends K
@@ -135,7 +136,7 @@ declare module 'mongoose' {
135136
*/
136137
type AddThisParameter<T, D> = {
137138
[K in keyof T]: T[K] extends (...args: infer A) => infer R
138-
? ThisParameter<T[K], unknown> extends unknown
139+
? IsUnknown<ThisParameter<T[K], unknown>> extends true
139140
? (this: D, ...args: A) => R
140141
: T[K]
141142
: T[K];

0 commit comments

Comments
 (0)