Skip to content

TypeScript does not return an error when assigning the result of a lean query to a variable of type InstanceType<Model<MyModel>> #14697

@nikzanda

Description

@nikzanda

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.4.4

Node.js version

20.10.0

MongoDB server version

6.0.2

Typescript version (if applicable)

5.4.5

Description

Reproduction link: https://stackblitz.com/edit/stackblitz-starters-9hjjfm?file=src%2Findex.ts

TypeScript should not allow me to assign the result of await UserModel.findOne().lean(); to the variable let user: UserInstance | null = null; in fact, the user.set or user.save instruction results in an error.

  let user: UserInstance | null = null;
  if (condition) {
    user = await UserModel.findOne().lean(); // Here it should report an error
    if (user) {
      user.set({
        name: 'John Doe',
      });
      await user.save();
    }
  }

The code below
image
image

results in an error when executed:
Screenshot 2024-06-28 at 18 24 06

Steps to Reproduce

  • Declare a variable of type InstanceType<Model<MyModel>>;
  • Assign the result of await MyModel.findOne().lean();
  • Call .set({ ... }) or .save() function of the variabile.

Expected Behavior

TypeScript should not allow the code to compile

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