node.js - 'this' 隐式具有类型 'any' 因为它没有类型 annotation.ts(2683)

标签 node.js typescript

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/

相关文章:

javascript - 如何使用 mocha sinon 模拟类异步/等待函数

javascript - putObject() 在大于 ~1MB 的文件上超时

ios - 当我使用 nativescript 从 iOS 发送表情符号字符时,为什么我会得到陌生的字符串

javascript - 如何在 Angular 中使用 IndexedDB?

Typescript:解决内置 javascript 的类型定义错误

android - HTML5 Canvas元素不会出现在已编译的Android Ionic中,但可以在浏览器“Ionic Serve”中使用

javascript - 在sequelize where查询中使用OR语句

javascript - Nodejs 代理脚本,不适用于 mod_deflate

javascript - 如何根据我运行的项目更改组件中的文本?

typescript - 抽象掉 typescript 中的泛型类型参数