Sequelize docs claim that it works with Typescript but in order for it to be useful in production one needs to use DB migration scripts. These can only be executed using the Sequelize CLI but this CLI seems to have no regard for Typescript at all. It only generates (and apparently runs) JS files. There is a "sequelize-cli-typescript" project on NPM but it's 4 years old! And the only answer on Stack Overflow to a related question is literally 6 words long, none of them useful: Using sequelize cli with typescript
My setup is like so:
I created a basic Node app with Typescript and a simple tsconfig.js
like so:
{
"compilerOptions": {
"allowJs": true,
"module": "commonjs",
"esModuleInterop": true,
"target": "es6",
"noImplicitAny": true,
"moduleResolution": "node",
"sourceMap": true,
"outDir": "dist",
"baseUrl": ".",
"paths": {
"*": [
"node_modules/*"
]
}
},
"include": [
"*"
]
}
I'm also using ESLint with the following .eslintrc
:
{
"root": true,
"parser": "@typescript-eslint/parser",
"plugins": [
"@typescript-eslint"
],
"extends": [
"airbnb-base", "airbnb-typescript/base"
],
"parserOptions": {
"project": "./tsconfig.json"
}
}
I then tried running the Sequelize CLI init command, npx sequelize-cli init
as described in the DB migrations documentation. This caused a file models/index.js
to be created with the following content:
'use strict';
const fs = require('fs');
const path = require('path');
const Sequelize = require('sequelize');
const basename = path.basename(__filename);
const env = process.env.NODE_ENV || 'development';
const config = require(__dirname + '/../config/config.json')[env];
const db = {};
let sequelize;
if (config.use_env_variable) {
sequelize = new Sequelize(process.env[config.use_env_variable], config);
} else {
sequelize = new Sequelize(config.database, config.username, config.password, config);
}
fs
.readdirSync(__dirname)
.filter(file => {
return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js');
})
.forEach(file => {
const model = require(path.join(__dirname, file))(sequelize, Sequelize.DataTypes);
db[model.name] = model;
});
Object.keys(db).forEach(modelName => {
if (db[modelName].associate) {
db[modelName].associate(db);
}
});
db.sequelize = sequelize;
db.Sequelize = Sequelize;
module.exports = db;
This causes my IDE (VS Code) to show an error:
Parsing error: "parserOptions.project" has been set for @typescript-eslint/parser. The file does not match your project config: models/index.js. The file must be included in at least one of the projects provided.
I have no idea what this is supposed to mean. I've read numerous explanations and none makes sense to me. I have allowJs set to true in tsconfig and include all. What am I missing? More importantly how can I use Typescript for DB migrations and CLI generated code?