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

使用Sequelize定义Model时触发TypeScript无限类型实例化错误

解决Sequelize + TypeScript 4.7.x的「Type instantiation is excessively deep and possibly infinite」错误

这个问题是TypeScript 4.7.x版本与Sequelize 6.21.0的类型系统冲突导致的——InferAttributes和InferCreationAttributes的递归类型定义在TS4.7的严格类型检查下触发了无限递归检测。以下是几种可行的解决办法:

方案1:降低TypeScript版本

将TypeScript降级到4.6.x系列(比如4.6.4),该版本不会触发这个类型检查问题。修改package.json中的版本后执行npm install或yarn install即可。

方案2:修改Model接口定义,避免递归引用

不用递归的InferAttributes<EshopModelI>,而是显式定义属性类型,再让Model接口继承:

import { DataTypes } from 'sequelize'
import sequelizeConn from '../services/sequelize'
import { Model } from 'sequelize'

// 显式定义模型的属性类型
interface EshopAttributes {
  eshop_id: number
}

// 定义创建实例时的属性(若有可选字段可在此调整)
interface EshopCreationAttributes extends EshopAttributes {}

// 让Model接口继承显式类型,避免递归
interface EshopModelI extends Model<EshopAttributes, EshopCreationAttributes>, EshopAttributes {}

const EshopModel = sequelizeConn.define<EshopModelI>("eshop", {
  eshop_id: {
    type: DataTypes.INTEGER,
    primaryKey: true
  }
})
export default EshopModel

方案3:升级Sequelize到兼容版本

将Sequelize升级到6.28.0及以上版本,这些版本修复了与TypeScript 4.7+的类型兼容性问题,优化了InferAttributes的递归逻辑,无需修改代码即可解决错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 12:55:19