userSchema.pre('save', async function(done) {
if (this.isModified('pass')) {
const hashed = await Password.toHash(this.get('pass'));
this.set('pass', hashed);
}
done();
});
我从“this”收到以下错误:
'this' implicitly has type 'any' because it does not have a type annotation.ts(2683)
我听说问题出在箭头键上,但我没有在回调函数中使用箭头键?我仍然收到错误消息。给了什么?
我也从“完成”中收到错误:
Parameter 'done' implicitly has an 'any' type.ts(7006)
会不会是 Visual Studio Code 的某种错误?
最佳答案
这不是 VS Code 或 TypeScript 中的错误。很简单,TypeScript 的调用中没有足够的信息来确定当 Mongoose 最终执行函数时 this
将绑定(bind)到什么。
假设您有一个名为 User
的类型,您可以使用显式的 this
类型注释来解决这个问题。
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();
});
请注意,用于指定 this
类型的语法是一种特殊语法,因为它不会在生成的 JavaScript 中发出参数:
function(this: X) {}
编译为
function() {}
关于node.js - 'this' 隐式具有类型 'any' 因为它没有类型 annotation.ts(2683),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62228176/