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

Typescript: Error Handling Middleware callback function params are implicitly set to 'any'. #12583

Closed
1 task done
MindeVieras opened this issue Oct 24, 2022 · 6 comments
Closed
1 task done
Labels
enhancement This issue is a user-facing general improvement that doesn't fix a bug or add a new feature typescript Types or Types-test related issue / Pull Request
Milestone

Comments

@MindeVieras
Copy link

MindeVieras commented Oct 24, 2022

Prerequisites

  • I have written a descriptive issue title

Mongoose version

6.6.7

Node.js version

18.11.0

MongoDB version

6.0.1

Operating system

macOS

Operating system version (i.e. 20.04, 11.3, 10)

12.6

Issue

I'm following this documentation [Error Handling Middleware](https://mongoosejs.com/docs/middleware.html#error-handling-middleware), and TypeScript does not infer the error middleware function arguments if three parameters are given.

userSchema.post('save', function (error, doc, next) { <------ All params implicitly has an 'any' type.
  if (error.name === 'MongoServerError' && error.code === 11000) {
    next(new Error('There was a duplicate key error'))
  } else {
    next()
  }
})

I know it is possible to set those types explicitly. However, it will lead to a bunch of boilerplate code, which should be inferred from ErrorHandlingMiddlewareFunction type.

My tsconfig.json:

{
  "compilerOptions": {
    "target": "es6",
    "module": "commonjs",
    "rootDir": "src",
    "outDir": "dist",
    "lib": [
      "es6"
    ],
    "removeComments": false,
    "strict": true,
    "declaration": true,
    "declarationDir": "types",
    "skipLibCheck": true,
    "esModuleInterop": true
  },
  "include": [
    "src",
    "test"
  ],
  "exclude": [
    "node_modules"
  ]
}

@MindeVieras MindeVieras added help This issue can likely be resolved in GitHub issues. No bug fixes, features, or docs necessary help wanted labels Oct 24, 2022
@IslandRhythms IslandRhythms added typescript Types or Types-test related issue / Pull Request and removed help This issue can likely be resolved in GitHub issues. No bug fixes, features, or docs necessary help wanted labels Oct 24, 2022
@IslandRhythms
Copy link
Collaborator

import * as mongoose from 'mongoose';

// 1. Create an interface representing a document in MongoDB.
interface IUser {
  name: string;
  email: string;
  avatar?: string;
}

// 2. Create a Schema corresponding to the document interface.
const userSchema = new mongoose.Schema<IUser>({
  name: { type: String, required: true },
  email: { type: String, required: true },
  avatar: String
});

userSchema.post('save', function (error, doc, next) {
  console.log('save hook triggered')
  console.log(error.name);
  console.log(doc.name)
});

// 3. Create a Model.
const User = mongoose.model<IUser>('User', userSchema);

run().catch(err => console.log(err));

async function run() {
  // 4. Connect to MongoDB
  await mongoose.connect('mongodb://localhost:27017/test');
  await mongoose.connection.dropDatabase();
  const user = new User({
    name: 'Bill',
    email: 'bill@initech.com',
    avatar: 'https://i.imgur.com/dM7Thhn.png'
  });
  await user.save();

  console.log(user.email); // 'bill@initech.com'
}

@MindeVieras
Copy link
Author

MindeVieras commented Oct 24, 2022

@IslandRhythms, thank you for the response, but I'm still getting the same typescript errors.

Screenshot 2022-10-24 at 18 30 48

Could this be typescript config issue itself? Would you mind sharing your tsconfig.json, please?

@vkarpov15
Copy link
Collaborator

@MindeVieras does TypeScript compilation actually fail, or are you just getting red lines in your editor?

@MindeVieras
Copy link
Author

@vkarpov15 thank you for the response. Yes, it still fails:

Screenshot 2022-11-01 at 20 24 35

@vkarpov15 vkarpov15 added the needs repro script Maybe a bug, but no repro script. The issue reporter should create a script that demos the issue label Nov 9, 2022
@vkarpov15 vkarpov15 added this to the 6.7.4 milestone Nov 9, 2022
@vkarpov15
Copy link
Collaborator

It looks like TypeScript struggles to distinguish between (this: ThisType, res: ResType, next: CallbackWithoutResultAndOptionalError) => void and (this: ThisType, err: NativeError, res: ResType, next: CallbackWithoutResultAndOptionalError) => void, maybe because it doesn't assume that number of arguments can be used to distinguish between 2 function overloads. If I delete the non-error-handling post() definitions, this code compiles fine.

We're probably going to have to add a new feature or way to define error handling middleware that TypeScript can distinguish.

@vkarpov15 vkarpov15 modified the milestones: 6.7.4, 6.8 Nov 23, 2022
@vkarpov15 vkarpov15 added enhancement This issue is a user-facing general improvement that doesn't fix a bug or add a new feature and removed needs repro script Maybe a bug, but no repro script. The issue reporter should create a script that demos the issue labels Nov 23, 2022
@vkarpov15
Copy link
Collaborator

See #12723, you'll have to do the following in 6.8 to help TypeScript out:

userSchema.post('save', { errorHandler: true }, function (error, doc, next) {
  if (error.name === 'MongoServerError' && error.code === 11000) {
    next(new Error('There was a duplicate key error'))
  } else {
    next()
  }
})

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement This issue is a user-facing general improvement that doesn't fix a bug or add a new feature typescript Types or Types-test related issue / Pull Request
Projects
None yet
Development

No branches or pull requests

3 participants