Skip to content

"this" context has "any" type in Schema methods option #14027

Closed
@ruxxzebre

Description

@ruxxzebre

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the bug has not already been reported

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:

schema.method("fullName", function fullName() {
    return this.firstName + " " + this.lastName;
});

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.

new Schema<IUser, UserModel, IUserMethods>
Screenshot 2023-11-01 at 20 05 27

However, If we do not provide IUserMethods into a Schema generic, this becomes a Document type, as it should.

new Schema<IUser, UserModel>
or
new Schema<IUser, UserModel, {}>
Screenshot 2023-11-01 at 20 06 26

@pshaddel thanks!

Steps to Reproduce

Declare types/interfaces for document, methods and model.

interface IUser {
    firstName: string;
    lastName: string;
}

// Put all user instance methods in this interface:
interface IUserMethods {
    fullName(): string;
}

// Create a new Model type that knows about IUserMethods...
type UserModel = Model<IUser, {}, IUserMethods>;

Initialise schema with methods, but without third generic type, and observe the result.

const schema = new Schema<IUser, UserModel>(
    {
        firstName: { type: String, required: true },
        lastName: { type: String, required: true },
    },
    {
        methods: {
            fullName() {
                return this.firstName + " " + this.lastName;
            },
        },
    }
);

Initialise schema with methods and third generic type (IUserMethods), and observe the result.

const schema = new Schema<IUser, UserModel, IUserMethods>(
    {
        firstName: { type: String, required: true },
        lastName: { type: String, required: true },
    },
    {
        methods: {
            fullName() {
                return this.firstName + " " + this.lastName;
            },
        },
    }
);

Expected Behavior

Methods declared in Schema's options.methods should infer this with a right type, including provided interface for methods.

Metadata

Metadata

Assignees

No one assigned

    Labels

    typescriptTypes or Types-test related issue / Pull Request

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions