Mongoose's loadClass() with TypeScript

六月ゝ 毕业季﹏ 提交于 2021-02-09 10:59:31

问题


Mongoose accepts an ES6 class as the basis for a schema.

The example from that link:

class PersonClass {

  get fullName() {
    return `${this.firstName} ${this.lastName}`;    // compiler error
  }

}

PersonSchema.loadClass(PersonClass);

The schema's properties are not defined in the class, so the TypeScript compiler says:

Property firstName does not exist on type PersonClass.

A hack is to use a dummy constructor:

constructor(readonly firstName: string, readonly lastName: string) { }

However that is hack, and harder to maintain.

Is there some other way to do this, without hacks?


回答1:


The trick is to use the this IPerson annotation:

get fullName(this IPerson) {
    return `${this.firstName} ${this.lastName}`;
}

Where IPerson is the corresponding interface for that schema.



来源:https://stackoverflow.com/questions/54723586/mongooses-loadclass-with-typescript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!