Skip to content

Commit f631093

Browse files
authored
Merge pull request #15750 from Automattic/vkarpov15/gh-15693
types: correct Model.schema type and fix unknown check for this param type in schema.methods
2 parents 113e801 + c2dc34d commit f631093

File tree

3 files changed

+31
-3
lines changed

3 files changed

+31
-3
lines changed

test/types/models.test.ts

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

types/models.d.ts

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

10181018
/** Schema the model uses. */
1019-
schema: Schema<TRawDocType>;
1019+
schema: TSchema;
10201020

10211021
/** Creates a `updateMany` query: updates all documents that match `filter` with `update`. */
10221022
updateMany(

types/utility.d.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ declare module 'mongoose' {
22
type IfAny<IFTYPE, THENTYPE, ELSETYPE = IFTYPE> = 0 extends 1 & IFTYPE
33
? THENTYPE
44
: ELSETYPE;
5-
type IfUnknown<IFTYPE, THENTYPE> = unknown extends IFTYPE ? THENTYPE : IFTYPE;
5+
type IsUnknown<T> = unknown extends T ? true : false;
66

77
type IsNotNever<T> = [T] extends [never] ? false : true;
88
type IsAny<T> = 0 extends 1 & T ? true : false;
@@ -155,7 +155,7 @@ declare module 'mongoose' {
155155
*/
156156
type AddThisParameter<T, D> = {
157157
[K in keyof T]: T[K] extends (...args: infer A) => infer R
158-
? ThisParameter<T[K], unknown> extends unknown
158+
? IsUnknown<ThisParameter<T[K], unknown>> extends true
159159
? (this: D, ...args: A) => R
160160
: T[K]
161161
: T[K];

0 commit comments

Comments
 (0)