【问题标题】:Sequelize in Node.js with TypeScript - Class constructor Model cannot be invoked without 'new'使用 TypeScript 在 Node.js 中进行 Sequelize - 没有“new”就无法调用类构造函数模型
【发布时间】:2020-05-10 06:14:15
【问题描述】:

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

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

未处理的拒绝类型错误:类构造函数模型不能 调用时不带“新”

据我了解,这不是 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 应该可以解决问题,但即使在这样的更改之后问题仍然存在。我在这里做错了什么已经没有想法了,所以我们将不胜感激。

【问题讨论】:

    标签: node.js typescript es6-class


    【解决方案1】:

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

    【讨论】:

    • 它在根目录下,叫做tsconfig.json。这是您放置打字稿配置设置的地方。
    【解决方案2】:

    转到tsconfig.json 文件。然后,将 target 更改为 es6,如下例所示:

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

    【讨论】:

    • 这对我有用。最初我将其设置为 es5。
    【解决方案3】:

    感谢https://stackoverflow.com/users/4344732/tran-son-hoang,将"module": "commonjs" 添加到tsconfig.josn 后我已经解决了问题

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

    【讨论】:

      猜你喜欢
      • 2018-10-20
      • 2021-05-24
      • 2021-12-23
      • 2017-09-29
      • 2018-09-19
      • 1970-01-01
      • 2015-12-24
      • 1970-01-01
      相关资源
      最近更新 更多