Skip to content

Typescript: schema type required argument, and this type #13797

Closed
@AbdelrahmanHafez

Description

@AbdelrahmanHafez

Prerequisites

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

Mongoose version

7.5.0

Node.js version

18.x

MongoDB server version

N/A

Typescript version (if applicable)

5.1.6

Description

In JS world, the document is accessible as an argument and as this for required functions.
In TS, however, we can not access those types.

Steps to Reproduce

The following test fails

function gh13797() {
  interface User {
    name: string;
    age: number;
  }

  const schemaWithArrowFunction = new Schema<User>({
    age: Number,
    name: {
      type: String,
      required(user) {
        expectType<User>(user);
        expectType<number>(user.age);
        return user.age > 30;
      }
    }
  });

  const schemaWithRegularFunction = new Schema<User>({
    age: Number,
    name: {
      type: String,
      required: function (user) {
        expectType<User>(user);
        expectType<User>(this);
        expectType<number>(user.age);
        expectType<number>(this.age);

        return user.age > 30;
      }
    }
  });
}

Expected Behavior

I expect it to pass.

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