【问题标题】:Defining a union type in a Mongoose schema using TypeScript使用 TypeScript 在 Mongoose 模式中定义联合类型
【发布时间】:2022-04-13 00:53:37
【问题描述】:

我像这样在 TypeScript 中定义了一个猫鼬模式。

 interface ISchema {
   prereqs: 'CONSENT' | string[]
}

 const newSchema = new Schema<ISchema>({
     prereqs: { type: Schema.Types.Mixed, required: true }
 })

我希望“prereqs”成为“常量字符串”和“字符串数组”之间的联合类型。所以我在猫鼬模式中将此字段定义为“Schema.Types.Mixed”,但编译器给了我这个错误

Type '{ type: typeof Schema.Types.Mixed; required: true; }' is not assignable to type 'SchemaDefinitionProperty<string[] | "CONSENT"> | undefined'.
Types of property 'type' are incompatible.
Type 'typeof Mixed' is not assignable to type '"string" | typeof String | StringConstructor | "String" | AnyArray<"string" | typeof String | StringConstructor | "String"> | AnyArray<...> | undefined'.
Types of construct signatures are incompatible.
Type 'new (path: string, options?: AnyObject | undefined, instance?: string | undefined) => Mixed' is not assignable to type 'new (path: string, options?: AnyObject | undefined, instance?: string | undefined) => String'.
Type 'SchemaType' is missing the following properties from type 'String': enum, lowercase, match, maxlength, and 3 more.

好吧,如果我在界面中将 prereqs 定义为 any,它将正常工作。但它会失去类型检查能力。

有没有办法解决这个问题?

【问题讨论】:

    标签: typescript mongoose


    【解决方案1】:

    肯定有一种方法可以保持架构验证并为字段添加联合功能。

    但个人认为 - 它稍微使代码不可读。

    您可以在此处参考此文档 - https://mongoosejs.com/docs/discriminators.html

    【讨论】:

      猜你喜欢
      • 2021-10-17
      • 2020-07-31
      • 1970-01-01
      • 2018-12-11
      • 2021-01-31
      • 2019-01-13
      • 2018-01-18
      • 2021-03-19
      • 1970-01-01
      相关资源
      最近更新 更多