Mongoose Schema 类型作为 TypeScript 的自定义接口?

Mongoose Schema type as a custom interface from TypeScript?

我想存储一个具有 StationRating 接口属性的自定义对象,有人可以帮我吗?

这是可能的,但它需要一些样板文件。问题是:

  • TS 中的接口和类型在发出的代码中不存在

  • 虽然您可以朝另一个方向前进 - 创建一个模式对象并从中创建一个 interface/type - 模式对象值必须是 constructors,例如 Number,它与 number 类型的东西不同。

但是您可以创建一个类型,将构造函数类型映射到它们的原始类型(例如 Numbernumber),然后使用它来将模式对象转换为您想要的类型:

type ConstructorMapping<T> =
    T extends NumberConstructor ? number :
    T extends StringConstructor ? string : never; // etc: continue as needed

const schemaObj = {
  score: Number,
  user_id: String,
  station_id: String,
  description: String,
};

type SchemaObj = typeof schemaObj;
type StationRating = {
    [prop in keyof SchemaObj]: ConstructorMapping<SchemaObj[prop]>
};

然后在调用new Schema时使用schemaObj,你也会有如下可用的类型:

type StationRating = {
    score: number;
    user_id: string;
    station_id: string;
    description: string;
}

值得吗?我不确定。对于较小的对象,也许不是。对于更大的物体,也许是这样。您可能更愿意只写出类型和架构对象。