Sequelize import having an issue with TypeScript

Shamoon
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
  });
}

Specifically, the db[model.name] = model; has a Typescript error:

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

How can I resolve this?

Shamoon

Resolved by adding an interface:

interface DbModel {
  [key: string]: any
}

and changing my code to:

  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)
    }
  })

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related