【发布时间】: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