I’m in trouble to make my model, with sequelize, User.js be recognized inside my UserController.ts, in typescript.
In the await User.findAll() part, it shows an error when running on the server, saying User is not defined. I’ve already changed the way I import this require, when I used import to import the User model, the IDE pointed to this error: “The ‘this’ context of type ‘typeof User’ is not assignable to method’s ‘this’ of type ‘ModelStatic’.
Type ‘typeof User’ is not assignable to type ‘NonConstructor’.
The types returned by ‘init(…)’ are incompatible between these types.”
the UserController.ts code, where is the problem:
import { Request, Response } from 'express';
var User = require("../model/User");
export class UserController {
async getAllUsers(req: Request, res: Response): Promise<Response> {
// const { id } = req.params;
try {
const user = await User.findAll(); // Here is the line appointed with problem
if (!user) {
return res.status(404).json({ error: 'Usuário não encontrado' });
}
return res.status(200).json(user);
} catch (error) {
return res.status(400).json({ error: error.message });
}
}
}
The User.js model file:
import Sequelize, { Model } from 'sequelize';
class User extends Model {
static init(sequelize) {
super.init(
{
name: { type: Sequelize.STRING },
email: { type: Sequelize.STRING },
password_hash: { type: Sequelize.STRING },
},
{
sequelize,
tableName: 'users'
}
);
}
}
export default User;
The route I’ve defined here. The file is UserRoute.js:
router.get('/', async function(req, res) {
res.render('./user/home', { users: UserController.getAllUsers() });
});
In this file I had managed to use the User model inside it and it worked.
The path of structure of these files are here:
src/route/UserRoute.js
src/model/User.js
src/controller/UserController.ts
My current package.json:
"dependencies": {
"@types/express": "^4.17.21",
"ejs": "^3.1.10",
"express": "^4.19.2",
"node-fetch": "2",
"pg": "^8.11.5",
"pg-hstore": "^2.3.4",
"sequelize": "^6.37.2"
},
"devDependencies": {
"@types/jest": "^29.5.12",
"eslint": "^7.32.0 || ^8.2.0",
"eslint-config-airbnb-base": "^15.0.0",
"eslint-config-prettier": "^9.1.0",
"eslint-plugin-import": "^2.25.2",
"eslint-plugin-prettier": "^5.1.3",
"jest": "^29.7.0",
"nodemon": "^3.1.0",
"prettier": "^3.2.5",
"sequelize-cli": "^6.6.2",
"sucrase": "^3.35.0",
"ts-jest": "^29.1.2"
}
Ideas to solve the problem with User class on typescript UserController class?