You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Express+Mongoose项目报ts(2347)未类型化函数不接受类型参数错误如何解决

报错原因

Untyped function calls may not accept type arguments.ts(2347) 出现在Schema泛型传参位置,本质是TypeScript无法识别Mongoose的Schema构造函数支持泛型参数,常见触发场景有三类:

  1. Mongoose版本过旧,未内置泛型支持
  2. 未正确导入Mongoose类型定义
  3. Schema泛型传参格式不符合要求
解决方案
  • 第一步:核对Mongoose版本
    Mongoose 6.x及以上版本已内置完整TypeScript类型定义,无需额外安装@types/mongoose依赖;如果使用Mongoose 5.x及以下版本,先执行命令安装类型依赖:
    npm i @types/mongoose -D
    
  • 第二步:修正Mongoose导入方式
    不要使用require全量导入后取属性的写法,该写法会导致TypeScript丢失类型推导,推荐使用ES模块导入:
    import { Schema, model, Model } from 'mongoose';
    
    如果项目强制使用CommonJS规范,修改导入格式为:
    import mongoose = require('mongoose');
    const Schema = mongoose.Schema;
    const model = mongoose.model;
    
  • 第三步:调整Schema泛型传参格式
    Mongoose的Schema构造函数需要同时传入文档类型、模型类型两个泛型参数才能正确推导,修改你的Schema定义代码:
    const UserSchema = new Schema<IUser, Model<IUser>>(
     {
       name: {
         type: String,
         required: true,
       },
       email: {
         type: String,
         required: true,
         unique: true,
         validate: [validator.isEmail, "Please provide a valid email"],
       },
       password: {
         type: String,
         required: true,
         minlength: 8,
       },
       isAdmin: {
         type: Boolean,
         required: true,
         default: false,
       },
     },
     {
       timestamps: true,
     }
    );
    
  • 第四步:修正模型定义与导出
    给model调用也加上泛型约束,同时将CommonJS导出改为TS兼容的格式:
    const UserModel = model<IUser>("User", UserSchema);
    // ES模块导出
    export default UserModel;
    // 如果必须用CommonJS导出,替换为:
    // export = UserModel
    
额外注意

如果业务逻辑需要使用timestamps配置自动生成的createdAt、updatedAt字段,需要将这两个字段补充到IUser接口定义中:

interface IUser{
  name: string;
  email: string;
  password: string;
  isAdmin: boolean;
  createdAt?: Date;
  updatedAt?: Date;
}

内容的提问来源于stack exchange,提问作者Lidor Dvir

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.23 21:36:03