使用Mongoose和TypeScript创建自定义验证时出错

时间:2018-10-23 12:07:51

标签: javascript mongodb typescript mongoose

 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'在类型'{不存在,类型:StringConstructor; 枚举:string [];必需:()=>任何; }'
  • 'required'隐式具有返回类型'any',因为它没有返回类型注释,并且在其返回表达式之一中直接或间接引用。

2 个答案:

答案 0 :(得分:1)

为了对required函数进行类型检查,TypeScript需要知道在调用this时将引用的对象类型required。默认情况下,TypeScript猜测(错误地)required将作为包含对象文字的方法被调用。由于Mongoose实际上会调用required并将this设置为您要定义的结构的文档,因此您需要为该文档类型定义一个TypeScript接口(如果您还没有一个TypeScript接口) ),然后为this函数指定一个required参数。

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;
       }
     }
   });

答案 1 :(得分:0)

tscongig.json 内的 compilerOptions 文件中,我更改了以下内容并且它起作用了:

"noImplicitThis": false, 
...
/* Raise error on 'this' expressions with an implied 'any' type. */