Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

types(schematypes): use DocType for instance method this #13822

Merged
merged 3 commits into from
Sep 8, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 @@
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);
});
}

Check warning on line 1220 in test/types/schema.test.ts

View workflow job for this annotation

GitHub Actions / Lint TS-Files

Newline required at end of file but not found
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