TS2351:不能将 'new' 用于类型缺少调用或构造签名的表达式。猫鼬

TS2351: Cannot use 'new' with an expression whose type lacks a call or construct signature. Mongoose

不确定我做错了什么,但我有这个 class/module:

import * as Mongoose from 'mongoose';
import * as _ from 'lodash';
import * as Promise from 'bluebird';
import { db } from '../lib/database';

let mongoose = Mongoose;

mongoose.Promise = Promise;


export class BaseModel  {

    constructor(schemaObj: {}, modelName: string, statics?: {}) {
      let Schema = new mongoose.Schema(schemaObj)

      Schema.statics.list = function () {
        return this.find()
      }

      Schema.statics.save = function (dataObj) {
        return this.save(dataObj)
      }

      if (statics) {
        for (let key in statics) {
          Schema.statics[key] = statics[key];
        }
      }
      
      return mongoose.model(modelName, Schema);
    }
    
}

let schema = {
  title:  String,
}

let Message = new BaseModel(schema, 'message');

let j = new Message({title: 'Hello World'}).save().then(function (res) {
  console.log(res);
})

一切正常,但 TypeScript 有问题:

TS2351: Cannot use 'new' with an expression whose type lacks a call or construct signature.

我知道我错过了一些东西,但我不知道是什么。

我认为问题不在您的代码中,您使用的唯一 new 运算符是创建一个新的 mongoose 方案,它看起来不错。可能问题出在猫鼬类型中。

您提到的错误通常在函数 returns 另一个函数而不是 class 实例时显示(例如:https://github.com/Microsoft/TypeScript/issues/2081)。

尝试将 typings 更新到最新版本或尝试将其降级到不同的较低版本。

(打字是如此神奇,在我们的项目中,有时我们需要修复一个特定的版本,因为即使是较新的路径版本也会破坏项目。)

尝试在导入 mongoose 时删除 * as。所以它会变成 import Mongoose from 'mongoose';