使用 TypeScript 在 Node.js 中进行 Sequelize - 如果没有“new”,则无法调用类构造函数模型

Fur*_*man 5 node.js typescript es6-class

我正在尝试在 Node.js + TypeScript 中使用 Sequelize。我正在尝试使用以下简单的代码:

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',
    });
});
Run Code Online (Sandbox Code Playgroud)

但是,当尝试运行编译的代码时,我收到以下错误:

未处理的拒绝类型错误:类构造函数模型无法在没有“new”的情况下调用

据我了解,这不是sequelize的问题:与javascript代码运行相同的代码运行没有问题,并在数据库正确的表中创建记录。我知道这是将 ES6 类转换为 ES5 的问题,但是我无法修复此错误。这是我的 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"
  ]
}
Run Code Online (Sandbox Code Playgroud)

从我在 Stackoverflow 中读到的类似问题和互联网上的各个网站来看,将编译器选项中的目标更改为 ES6 应该可以解决问题,但即使在这样的更改之后,问题仍然会发生。我已经不知道我在这里做错了什么,所以非常感谢您的帮助。

小智 2

尝试将tsconfig.json中的目标更改为“ES2017”。为我解决了问题。