【问题标题】:mongoose virtuals with typescript error - The containing arrow function captures the global value of 'this' which implicitly has type 'any'mongoose virtuals with typescript error - 包含箭头函数捕获“this”的全局值,该值隐含类型为“any”
【发布时间】:2019-06-24 00:31:04
【问题描述】:

我正在尝试使用带有 typescript 的 mongoose virtuals。并且无法使其工作。我收到与在代码中使用它相关的错误。我检查了许多参考资料,但找不到参考资料来完成这项工作。

"[ts] 包含箭头函数捕获隐含类型为 'any' 的 'this' 的全局值。[7041]"

export const UserSchema = new Schema({
    firstName: {
        type: String
    },
    lastName: {
        type: String
    },
    roleId: {
        alias: "group",
        type: String
    }
}, {
    toJSON: {
        transform: (doc, ret, options) => {
            delete ret.id ;
            delete ret.roleId ;
            return ret ;
        },
        virtuals: true,
    }
});

UserSchema.virtual("username").get(() => {
    return this.firstName + " " + this.lastName ;
}) ;

我期待一个新属性“username”,它结合了“firstName lastName”的值

替代代码但同样的错误 -

UserSchema.virtual("username").get(function() {
    return this.firstName + " " + this.lastName ;
}) ;

【问题讨论】:

  • this 的引用不能绑定在箭头函数中,它总是指向全局范围。如果您需要 this 来引用其他内容,请不要使用箭头函数。

标签: typescript mongoose


【解决方案1】:

根据定义,箭头函数从声明上下文中捕获this。由于您直接在模块中定义函数,这将是全局对象。

你想要一个常规的函数。一个常规函数,当在一个对象上调用时,会将this 作为调用它的实际对象传递给它。

您还需要为 this 添加类型注释(取决于您的严格设置,但您提到您尝试了常规功能,因此这可能是问题所在),this: any 或更具体的东西来告诉您所做的打字稿不会误访问this

UserSchema.virtual("username").get(function(this: { firstName: string, lastName: string}) {
  return this.firstName + " " + this.lastName ;
}) ;

【讨论】:

    【解决方案2】:

    我们还可以创建一个用户界面并使其成为这样:

    IUser extends mongoose.Document{
    firstname:string,
    lastname:string
    }
    
    UserSchema.virtual("username").get(function(this:IUser) {
      return this.firstName + " " + this.lastName ;
    }) ;
    

    【讨论】:

      猜你喜欢
      • 2019-06-08
      • 2020-02-20
      • 2020-12-17
      • 2021-12-11
      • 1970-01-01
      • 2019-08-04
      • 2018-08-23
      • 2017-06-16
      • 2020-09-25
      相关资源
      最近更新 更多