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.
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__/*"]
}
try changing target to "ES2017" in tsconfig.json. solved the proplem for me.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With