问题
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