Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sequelize in Node.js with TypeScript - Class constructor Model cannot be invoked without 'new'

I'm trying to use Sequelize in Node.js + TypeScript. I'm trying to use following simple code:

import {Sequelize, Model, DataTypes} from 'sequelize';

const sequelize = new Sequelize('base', 'user', 'pass', {dialect: 'mysql'});

class User extends Model {
}
User.init({
    id: {
        type: DataTypes.INTEGER.UNSIGNED,
        autoIncrement: true,
        primaryKey: true,
        unique: true,
    },
    login: {
        type: DataTypes.STRING(255),
        allowNull: false,
        unique: true,
    },
    password: {
        type: DataTypes.STRING(255),
        allowNull: false,
    },
}, {
    tableName: 'users',
    sequelize,
});

sequelize.sync().then(() => {
    User.create({
        login: 'aaaa',
        password: 'bbbb',
    });
});

However when trying to run compiled code, I'm getting following error:

Unhandled rejection TypeError: Class constructor Model cannot be invoked without 'new'

From what I understand, this is not a problem with sequelize: same code run as javascript code runs with no problem and creates record in database proper table. I know this is a problem with transpiling ES6 classes to ES5, however I can't get this error fixed. This is my tsconfig.json:

{
  "compilerOptions": {
    "experimentalDecorators": true,
    "outDir": "./dist",
    "noImplicitAny": true,
    "noImplicitReturns": true,
    "module": "esnext",
    "target": "es5",
    "sourceMap": true,
    "moduleResolution": "node",
    "lib": ["es5", "dom", "esnext"],
    "jsx": "react",
    "typeRoots": ["./common/typings", "./node_modules/@types"]
  },
  "exclude": [
    "node_modules"
  ]
}

From what I've read in Stackoverflow similiar questions and various sites on internet, changing target in compiler options to ES6 should resolve problem, but even after such change problem still occurs. I'm running out of ideas what I've done wrong here, so help will be greatly appreciated.

like image 213
Furman Avatar asked Jan 23 '20 21:01

Furman


2 Answers

Go to the tsconfig.json file. Then, change target to es6 like the sample below:

{
  "compilerOptions": {
    "target": "es6",
    "module": "commonjs",
    "declaration": true,
    "outDir": "./lib",
    "strict": true
  },
  "include": ["src"],
  "exclude": ["node_modules", "**/__tests__/*"]
}
like image 107
Tran Son Hoang Avatar answered Oct 18 '22 19:10

Tran Son Hoang


try changing target to "ES2017" in tsconfig.json. solved the proplem for me.

like image 2
Nick Chibuikem Avatar answered Oct 18 '22 20:10

Nick Chibuikem