Skip to content

Commit

Permalink
Merge pull request #13822 from pshaddel/master
Browse files Browse the repository at this point in the history
types(schematypes): use DocType for instance method this
  • Loading branch information
vkarpov15 authored Sep 8, 2023
2 parents 5eb374d + 8debef7 commit 8df3699
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 1 deletion.
35 changes: 35 additions & 0 deletions test/types/schema.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1183,3 +1183,38 @@ function gh13780() {
type InferredType = InferSchemaType<typeof schema>;
expectType<bigint | undefined>(null as unknown as InferredType['num']);
}

function gh13800() {
interface IUser {
firstName: string;
lastName: string;
someOtherField: string;
}
interface IUserMethods {
fullName(): string;
}
type UserModel = Model<IUser, {}, IUserMethods>;

// Typed Schema
const schema = new Schema<IUser, UserModel, IUserMethods>({
firstName: { type: String, required: true },
lastName: { type: String, required: true }
});
schema.method('fullName', function fullName() {
expectType<string>(this.firstName);
expectType<string>(this.lastName);
expectType<string>(this.someOtherField);
expectType<IUserMethods['fullName']>(this.fullName);
});

// Auto Typed Schema
const autoTypedSchema = new Schema({
firstName: { type: String, required: true },
lastName: { type: String, required: true }
});
autoTypedSchema.method('fullName', function fullName() {
expectType<string>(this.firstName);
expectType<string>(this.lastName);
expectError<string>(this.someOtherField);
});
}
2 changes: 1 addition & 1 deletion types/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -293,7 +293,7 @@ declare module 'mongoose' {
loadClass(model: Function, onlyVirtuals?: boolean): this;

/** Adds an instance method to documents constructed from Models compiled from this schema. */
method<Context = any>(name: string, fn: (this: Context, ...args: any[]) => any, opts?: any): this;
method<Context = THydratedDocumentType>(name: string, fn: (this: Context, ...args: any[]) => any, opts?: any): this;
method(obj: Partial<TInstanceMethods>): this;

/** Object of currently defined methods on this schema. */
Expand Down

0 comments on commit 8df3699

Please sign in to comment.