import mongoose, { Schema, model } from "mongoose";
var breakfastSchema = new Schema({
eggs: {
type: Number,
min: [6, "Too few eggs"],
max: 12
},
bacon: {
type: Number,
required: [true, "Why no bacon?"]
},
drink: {
type: String,
enum: ["Coffee", "Tea"],
required: function() {
return this.bacon > 3;
}
}
});
我在运行这段代码时遇到的两个错误是:
- 属性“bacon”不存在于类型“{ type: StringConstructor; 枚举:字符串[];必需:() => 任何; }'
- “required”隐式具有返回类型“any”,因为它没有返回类型注释,并且在其返回表达式之一中被直接或间接引用。
最佳答案
为了对 required
函数进行类型检查,TypeScript 需要知道在调用 required
时 this
将引用什么类型的对象.默认情况下,TypeScript 猜测(错误地)required
将作为包含对象文字的方法被调用。由于 Mongoose 实际上会调用 required
并将 this
设置为您正在定义的结构的文档,因此您需要为该文档类型定义一个 TypeScript 接口(interface)(如果您还没有),然后为 required
函数指定一个 this
参数。
interface Breakfast {
eggs?: number;
bacon: number;
drink?: "Coffee" | "Tea";
}
var breakfastSchema = new Schema({
eggs: {
type: Number,
min: [6, "Too few eggs"],
max: 12
},
bacon: {
type: Number,
required: [true, "Why no bacon?"]
},
drink: {
type: String,
enum: ["Coffee", "Tea"],
required: function(this: Breakfast) {
return this.bacon > 3;
}
}
});
关于javascript - 使用带 typescript 的 Mongoose 创建自定义验证时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52948723/