Furman
Furman

Reputation: 2395

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.

Upvotes: 5

Views: 5507

Answers (3)

Nikolay Podolnyy
Nikolay Podolnyy

Reputation: 1091

Thanks to https://stackoverflow.com/users/4344732/tran-son-hoang, I've solved issues after adding "module": "commonjs" to tsconfig.josn

"compilerOptions": {
    ...
    "module": "commonjs",
    ...
  },

Upvotes: 0

Hoang Subin
Hoang Subin

Reputation: 7400

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__/*"]
}

Upvotes: 3

Nick Chibuikem
Nick Chibuikem

Reputation: 36

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

Upvotes: 2

Related Questions