lin*_*ram 5 mongoose node.js typescript
我目前正在将我的 API 从 JS 转换为 TS。然而,我在猫鼬和打字稿方面遇到了一些困难。具体来说,this在我的实例方法中不可用。
我的代码:
AccountSchema.methods.comparePassword = async function (candidatePassword: string) {
const isMatch = await bcrypt.compare(candidatePassword, this.password);
return isMatch;
};
Run Code Online (Sandbox Code Playgroud)
this当引用函数而不是实际文档时,它会生成以下错误:
“函数”类型的参数不可分配给“字符串”类型的参数。
但是,根据Mongoose 的文档,不应该有错误,this应该参考实际文档。
这实际上指的是:
this: {
[name: string]: Function;
}
Run Code Online (Sandbox Code Playgroud)
我如何定义我的架构:
const AccountSchema = new mongoose.Schema<IAccount>({...})
Run Code Online (Sandbox Code Playgroud)
我的方法与 JS 配合得很好,所以我知道它与 TypeScript 有关。Mongoose 文档确认我的实现是定义实例方法的正确方法,所以我很困惑为什么它不起作用。
是否有我不知道的在猫鼬中声明和使用实例方法的特定 TS 方式?
任何帮助将不胜感激!
我所需要的只是this该函数的一个参数。this这在 TS 中很特殊,它指定函数内的类型。
就像这样:
async function (this: IAccount, candidatePassword: string) { ... }
Run Code Online (Sandbox Code Playgroud)
this参数不是显式传递的,因此新参数不会改变函数的调用方式。
| 归档时间: |
|
| 查看次数: |
1423 次 |
| 最近记录: |