Reputation:
userSchema.pre('save', async function(done) {
if (this.isModified('pass')) {
const hashed = await Password.toHash(this.get('pass'));
this.set('pass', hashed);
}
done();
});
I am getting the following error from "this":
'this' implicitly has type 'any' because it does not have a type annotation.ts(2683)
I heard the problem came from the arrow key, but I am not using an arrow key for the callback function? I am still getting an error. What gives?
I am also getting an error from "done":
Parameter 'done' implicitly has an 'any' type.ts(7006)
Could it be some kind of bug with Visual Studio Code?
Upvotes: 2
Views: 3341
Reputation: 31803
It's not a bug in VS Code or in TypeScript. It is simply that there is not enough information from the call for TypeScript to determine what this
will be bound to when the function is ultimately executed by Mongoose.
Assuming you have a type called User
, you can fix this with an explicit this
type annotation.
userSchema.pre('save', async function(this: User, done) {
if (this.isModified('pass')) {
const hashed = await Password.toHash(this.get('pass'));
this.set('pass', hashed);
}
done();
});
Note that the syntax used to specify the type of this
, is a special syntax in that it does not emit a parameter in the resulting JavaScript:
function(this: X) {}
compiles to
function() {}
Upvotes: 7
Reputation: 1550
Have you tried doing the following, i've had this same issue and I worked around like so...
// We generally explicitly provide a type to the arguments we are using...
userSchema.pre('save', async function(done: any) {
const self: any = this;
if (this.isModified('pass')) {
const hashed = await Password.toHash(self.get('pass'));
self.set('pass', hashed);
}
done();
});
From what I've come to understand, the error seeds from the typescript config which can be modified for implicit typings in order to not show the error.
Upvotes: -1