在使用TypeScript编写Node.js中的Sequelize时,遇到了一个问题:类构造函数Model不能在没有'new'的情况下被调用。

5

我正在尝试在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',
    });
});

然而,当我尝试运行编译后的代码时,出现以下错误:

未处理拒绝TypeError:无法调用 Class 构造函数 Model,必须使用'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"
  ]
}

据我在Stackoverflow类似问题和互联网上的各个网站所读,将编译器选项中的目标更改为ES6应该解决问题,但即使进行了这样的更改,问题仍然存在。我已经不知道在这里做错了什么,因此非常需要帮助。

3个回答

3

前往tsconfig.json文件,然后将target更改为es6,如下示例:

{
  "compilerOptions": {
    "target": "es6",
    "module": "commonjs",
    "declaration": true,
    "outDir": "./lib",
    "strict": true
  },
  "include": ["src"],
  "exclude": ["node_modules", "**/__tests__/*"]
}

1
这对我有用。最初我将其设置为es5。 - aaronmbmorse
我使用了ES6或ESNext,但仍然出现了这个错误。 - Ionel Lupu

2

尝试在 tsconfig.json 中将目标更改为"ES2017"。这对我解决了问题。


它位于根目录下,名为tsconfig.json。这是您放置TypeScript配置设置的地方。 - Nick Chibuikem

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接