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

如何在前端TypeScript代码中使用Sequelize类

问题描述

我已完成Sequelize模型的配置且运行正常,以下是实现方式简化示例:

//--- db.ts ---
export function db(): Sequelize{
  const sequelize = new Sequelize({
    dialect: 'sqlite',
    storage: 'DB.sqlite'
  })

  Thing.init({
    name:{ type: DataTypes.STRING },
  }, {
    sequelize //connection instance
  })
  
  return sequelize
}

export class Thing extends Model{}

我希望能在应用的前端、后端代码中全局使用Thing数据类型,从而在VS Code中获得该类可用属性的完善TypeScript智能提示支持。

但在前端代码(技术栈为Svelte)中按如下方式使用时,出现了类型错误:

<script lang="ts">
import type { Thing } from '$lib/db'

var thingOne:Thing? = null //<-- !! JSDoc types can only be used inside documentation comments !!
</script>

除此之外,尝试执行如下实例化操作时,还会出现严重的报错与异常行为:

var newThing = new Thing() 
//Build failure: Could not resolve "pg-hstore" (Sequelize may be choking since I don't use Postgres)

我接触TypeScript与Sequelize的时间较短,想咨询是否无法在前后端JavaScript/TypeScript代码中复用自定义的Thing类?


解决方案
  • 不要直接在前端引入带Sequelize运行时逻辑的文件
    Sequelize是纯后端运行的ORM库,依赖Node.js环境、各类数据库驱动等后端专属资源,前端环境无法运行。直接引入后端的db.ts会让打包工具尝试把Sequelize全量依赖打包进前端代码,就会触发pg-hstore这类数据库依赖缺失的构建错误。所有数据库实例化、查询操作都必须放在后端实现,前端只通过接口请求和后端交互,绝对不能在前端代码中new Sequelize的Model实例。

  • 修复TypeScript语法错误
    你写的var thingOne:Thing? = null是错误语法:TS中?只能用来标记接口/类的可选属性,不能直接放在类型后面。要声明一个可以为null的变量,需要用联合类型:

var thingOne: Thing | null = null

把?放在类型名后,TS会将其识别为非法的JSDoc写法,才会抛出对应的提示错误。

  • 前后端复用类型的正确方式:分离类型定义与运行时代码
    要实现前后端类型提示一致,必须把纯类型定义和带运行时逻辑的后端代码拆开:
    1. 新建公共类型文件(比如$lib/types/thing.ts),只写纯TS接口,不引入任何后端依赖,前后端都可以安全引入这个文件:
    export interface IThing {
      id?: number
      name: string
      createdAt?: Date
      updatedAt?: Date
    }
    
    1. 后端Sequelize模型定义时继承这个公共接口,获得完整类型提示:
    // db.ts 仅在后端代码中引入,不要暴露给前端
    import { Model, DataTypes, Sequelize } from 'sequelize'
    import type { IThing } from '$lib/types/thing'
    
    export function db(): Sequelize{
      const sequelize = new Sequelize({
        dialect: 'sqlite',
        storage: 'DB.sqlite'
      })
    
      Thing.init({
        name:{ type: DataTypes.STRING },
      }, {
        sequelize
      })
      
      return sequelize
    }
    
    export class Thing extends Model<IThing> implements IThing {}
    
    1. 前端代码只引入公共类型文件使用,完全不碰后端的Sequelize逻辑:
    <script lang="ts">
    import type { IThing } from '$lib/types/thing'
    
    let thingOne: IThing | null = null
    </script>
    

这种写法既可以保证前后端拿到完全一致的类型提示,又能从根源上避免后端依赖被打包进前端导致的构建错误。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 01:48:46