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
Comments
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'
} |
@IslandRhythms, thank you for the response, but I'm still getting the same typescript errors. Could this be typescript config issue itself? Would you mind sharing your tsconfig.json, please? |
@MindeVieras does TypeScript compilation actually fail, or are you just getting red lines in your editor? |
@vkarpov15 thank you for the response. Yes, it still fails: |
It looks like TypeScript struggles to distinguish between We're probably going to have to add a new feature or way to define error handling middleware that TypeScript can distinguish. |
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()
}
}) |
Prerequisites
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.
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:
The text was updated successfully, but these errors were encountered: