Problem
After upgrading to TypeScript 3.4, I found that some of my Mongoose middleware functions were failing type checking.
Error Message from TypeScript:
model.ts:19:8 - error TS7017: Element implicitly has an 'any' type because type 'typeof globalThis' has no index signature.
19 this.modified = new Date();
Schema Definition:
Schema.pre("save", next => {
this.modified = new Date();
next();
});
Attempts Made to Resolve
Upon using TSLint, it recommended to first cast this
to unknown
and then cast it to the model type as a workaround.
Schema.pre("update", next => {
(<Model>(<unknown>this)).modified = new Date();
next();
});
Although this method seems to work, it is not the most elegant or intuitive solution.
Seeking Suggestions
I am looking for a cleaner way to tackle this issue without having to disable any TypeScript rules. Any suggestions?