【发布时间】:2015-01-30 00:25:24
【问题描述】:
我正在尝试将在 nodejs 上使用猫鼬的现有项目转换为 Typescript。但是,我在一些回调函数中定义 this 的形状时遇到了问题。 例如,我的用户对象定义如下(大幅缩减以关注问题):
export class UserAPI{
userSchema: mongoose.Schema
constructor(){
this.userSchema = new mongoose.Schema({name: String,
email: {type:String, lowercase: true}
});
this.userSchema.virtual('password').set(function(password: string){
this._password = password;
}).get(function(){
return this._password;
});
}
}
上面的最后一行(返回 this._password)导致打字错误。据我了解,get 和 set 回调函数的范围是由 mongoose 设置的。显然,typescript 不知道回调函数中 this 对象的形状,从而导致编译器错误。有人可以帮助我了解如何克服这个错误吗?
【问题讨论】:
标签: node.js mongodb mongoose typescript