Mongoose 的 loadClass() 和 TypeScript [英] Mongoose's loadClass() with TypeScript
本文介绍了Mongoose 的 loadClass() 和 TypeScript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Mongoose 接受 ES6 类作为架构的基础.
Mongoose accepts an ES6 class as the basis for a schema.
来自该链接的示例:
class PersonClass {
get fullName() {
return `${this.firstName} ${this.lastName}`; // compiler error
}
}
PersonSchema.loadClass(PersonClass);
架构的属性没有在类中定义,所以 TypeScript 编译器说:
The schema's properties are not defined in the class, so the TypeScript compiler says:
PersonClass 类型上不存在属性 firstName.
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?
推荐答案
诀窍是使用 this IPerson
注释:
get fullName(this IPerson) {
return `${this.firstName} ${this.lastName}`;
}
其中 IPerson
是该模式的相应接口.
Where IPerson
is the corresponding interface for that schema.
这篇关于Mongoose 的 loadClass() 和 TypeScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文