Home > Net >  How to use Schema.virtual in typescript?
How to use Schema.virtual in typescript?

Time:09-28

I was using schema.virtual property in js but now i want to use it with tyescript and getting error. this is my code

UserSchema.virtual('fullname').get(function () {
  return `${this.firstName} ${this.lastName}`
});

I am facing this error

this' implicitly has type 'any' because it does not have a type annotation.

CodePudding user response:

There are a few solutions to work around this specific problem, for example declaring an interface for typing this, but in my experience this will create other issues (one being that doc.fullname will cause an error because TS isn't smart enough to know fullname has been added as a virtual).

The easiest way to solve this is to make virtuals part of the Schema declaration:

const UserSchema = new mongoose.Schema({
  firstName : String,
  lastName  : String,
  ...
}, {
  virtuals : {
    fullname : {
      get() {
        return `${this.firstName} ${this.lastName}`;
      }
    }
  }
});
  • Related