Home > Net >  How to Use Sequelize Class in Front-end TypeScript Code
How to Use Sequelize Class in Front-end TypeScript Code

Time:06-16

I have my Sequelize models set up and working. Here's a simplified example how how I've done it:

//--- 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{}

I want to be able to use the Thing data type throughout my app on both the front-end and back-end so that I get nice TypeScript support in VS Code for the properties available on my class.

But when I do this in my front-end code (which happens to be Svelte) I get a type error:

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

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

I also get crazy errors and behavior if I ever try and do this:

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

I'm relatively new to TypeScript and Sequelize. Am I not allowed to use my Thing class throughout my front and back-end JS?

CodePudding user response:

Sequelize wants access to the database (via NodeJS api's) and is not available in the Frontend.

A type import: import type { Thing } from "$lib/db"; should be allowed, this statement is removed after typescript compilation.
But is it only for type checking, and because real class can't be used it's not very useful.

  • Related