typescript - Sequelize 导入有 TypeScript 问题

标签 typescript sequelize.js

const _ = require('lodash');
const fs = require('fs');
const path = require('path');
const pg = require('pg');
require('pg-parse-float')(pg);

const Sequelize = require('sequelize');

interface ImportedModel {
  name: string
}

export function models () {
  const dbOptions = {
    dialect: 'postgres',
    protocol: 'postgres',
    logging: false,
    // logging: console.log,
    dialectOptions: {
      ssl: false // TODO: Need to set ssl to true
    }
  };

  const dbUrl = process.env.DB_URL;
  const sequelize = new Sequelize(dbUrl, dbOptions);

  let db: Object = {};

  const modelPath = `${process.cwd()}/models`;
  fs.readdirSync(modelPath).forEach((file: String) => {
    if (file !== 'index.js' && path.extname(file) === '.js') {
      let model: ImportedModel = sequelize.import(path.join(modelPath, file));
      db[model.name] = model;
    }
  });

  Object.keys(db).forEach((modelName: String) => {
    if ('associate' in db[modelName]) {
      db[modelName].associate(db);
    }
  });

  return _.assign(db, {
    sequelize: sequelize,
    Sequelize: Sequelize
  });
}

具体来说,db[model.name] = model; 有一个 Typescript 错误:

[ts] Element implicitly has an 'any' type because type 'Object' has no index signature.

我该如何解决?

最佳答案

通过添加接口(interface)解决:

interface DbModel {
  [key: string]: any
}

并将我的代码更改为:

  let db: DbModel = {}

  const modelPath = `${process.cwd()}/models`
  fs.readdirSync(modelPath).forEach((file: String) => {
    if (file !== 'index.js' && path.extname(file) === '.js') {
      let model: ImportedModel = sequelize.import(path.join(modelPath, file))
      db[model.name] = model
    }
  })

  Object.keys(db).forEach((modelName: string) => {
    if ('associate' in db[modelName]) {
      db[modelName].associate(db)
    }
  })

关于typescript - Sequelize 导入有 TypeScript 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50377182/

相关文章:

typescript - 为什么 TypeScript 编译器不能正确处理嵌套对象过滤?

javascript - 在 typescript 中循环遍历文本文件

typescript - 使用 FormBuilder Angular 2 绑定(bind)选择列表

javascript - 使用关联的实例创建 - Sequelize

Javascript 对象属性名称

javascript - Angular - 发出的事件无法到达父组件

mysql - 如何使用sequelize查找三表数据?

javascript - async.waterfall 不会在最后呈现

postgresql - 继承重命名索引

mysql - 关联表Sequelize js中获取自定义字段的方法