【问题标题】:How can the shape of this variable be defined in typescript callback functions如何在打字稿回调函数中定义这个变量的形状
【发布时间】: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


    【解决方案1】:

    显然,typescript 不知道回调函数中 this 对象的形状,从而导致编译器错误。

    这不应该是编译错误,因为 this 被假定为 any 类型,除非您使用的是 lambda (=>),而您的代码示例中并非如此。

    定义它的形状最好的办法是执行var foo:SomeType = this 之类的操作,然后使用foo 而不是this。原因:这是一个未解决的问题 (https://github.com/Microsoft/TypeScript/issues/229)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-12-28
      • 2018-12-27
      • 1970-01-01
      • 2020-09-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多