-
-
Notifications
You must be signed in to change notification settings - Fork 3.8k
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
"this" context has "any" type in Schema methods option #14027
Comments
@ruxxzebre Quick workaround: If you do not pass const schema = new Schema<IUser, UserModel>(
{
firstName: { type: String, required: true },
lastName: { type: String, required: true },
},
{
methods: {
fullName() {
return this.firstName + " " + this.lastName;
},
},
}
); |
Yes It works, as stated in ticket. However methods are not appearing in this at all. The thing is that it's currently not possible to have access to typings of methods from other methods (if we're not speaking of schema.method(...)) |
Made a workaround for my project, looks like this: type AddThisParameter<T, Doc> = {
[K in keyof T]: T[K] extends (...args: infer A) => infer R
? (this: Doc, ...args: A) => R
: T[K];
};
type HydratedUserDocument = HydratedDocument<
FlatRecord<IUser>,
IUserMethods
>;
export const userSchema = new mongoose.Schema<
IUser,
UserModel,
AddThisParameter<IUserMethods, HydratedUserDocument>
>( |
@pshaddel created a pull request targeted to this specific issue. |
Prerequisites
Mongoose version
8.0.0 (same case as 7.2.2)
Node.js version
20.5.0 (same case as 18.0.0)
MongoDB server version
7.0
Typescript version (if applicable)
5.2.2 (recently updated, same case with 4.8.4)
Description
As stated here, issue with this context was fixed, if we declare methods like this:
But, if we're trying to specify methods in schema's method option AND provide IUserMethods into a Schema generic, this becomes any once again.
However, If we do not provide IUserMethods into a Schema generic, this becomes a Document type, as it should.
@pshaddel thanks!
Steps to Reproduce
Declare types/interfaces for document, methods and model.
Initialise schema with methods, but without third generic type, and observe the result.
Initialise schema with methods and third generic type (IUserMethods), and observe the result.
Expected Behavior
Methods declared in Schema's options.methods should infer this with a right type, including provided interface for methods.
The text was updated successfully, but these errors were encountered: