gpt4 book ai didi

node.js - Typescript & Mongoose - "this"在实例方法中不可用

转载 作者:行者123 更新时间:2023-12-04 08:15:53 26 4
gpt4 key购买 nike

我目前正在将我的 API 从 JS 转换为 TS。但是,我在使用 Mongoose 和 typescript 时遇到了一些困难。具体来说,this 在我的实例方法中不可用。

我的代码:

AccountSchema.methods.comparePassword = async function (candidatePassword: string) {
const isMatch = await bcrypt.compare(candidatePassword, this.password);
return isMatch;
};

这会生成以下错误,因为 this 指的是函数而不是实际文档:

Argument of type 'Function' is not assignable to parameter of type 'string'.

然而,根据Mongoose's documentation ,应该不会有错误,因为 this 应该引用实际文档。

这实际上指的是什么:

this: {
[name: string]: Function;
}

我如何定义我的模式:

const AccountSchema = new mongoose.Schema<IAccount>({...})

我的方法适用于 JS,所以我知道它与 TypeScript 有一定关系。 Mongoose documentation确认我的实现是定义实例方法的正确方法,所以我很困惑为什么它不起作用。

是否有一种我不知道的在 mongoose 中声明和使用实例方法的特定 TS 方式?

如有任何帮助,我们将不胜感激!

最佳答案

我所需要的只是该函数的一个 this 参数。 That 在 TS 中比较特殊,指定函数内 this 的类型。

像这样:

async function (this: IAccount, candidatePassword: string) { ... }

this 参数未显式传递,因此新参数不会改变函数的调用方式。

关于node.js - Typescript & Mongoose - "this"在实例方法中不可用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65704763/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com