Based on the answer in How to register same mongoose hook for multiple methods?
const hooks = [ 'find', 'findOne', 'update' ];
UserSchema.pre( hooks, function( next ) {
// stuff
}
The code above works fine when not using TypeScript in strict mode. As soon as I enable strict mode, it complains: No overload matches this call.
How can I adjust the code to fix this? I can't seem to find much documentation about it, most documentation just offers examples of how to do it for a single method instead of multiple at a time.
The inferred type of your
hooksvariable isstring[].Schema.prehas various overloads:As the error message tells you, none of these accepts
string[]as themethodargument, because there are plenty of valid string values that are not valid method names.However if you are more specific about your intentions, e.g. using the query middleware type:
you can satisfy the compiler (and get the values checked for any typos, e.g. it could tell you if
findonewas accidentally used instead offindOne):Alternatively, you could just inline the array:
Note that using a type assertion, as suggested in your comment above, is not the right way to go about this. When you do that, rather than letting the compiler check the values you insist to it that they're right, so it can't catch typos for you: