Reputation: 71
I currently do the following search
const user: any = await UserModel.findOne({
where: {
email: email,
},
});
I'm typing with any because I need to use some table columns like user.username and user.password, but I don't want to use any.
UserModel:
const UserModel = db.define("users", {
id: {
type: DataTypes.INTEGER,
autoIncrement: true,
allowNull: false,
primaryKey: true,
},
username: {
type: DataTypes.STRING,
allowNull: false,
},
email: {
type: DataTypes.STRING,
allowNull: false,
},
password: {
type: DataTypes.STRING,
allowNull: false,
},
access_level: {
type: DataTypes.INTEGER,
allowNull: false,
},
biography: {
type: DataTypes.STRING,
allowNull: true,
},
profile_image: {
type: DataTypes.BLOB("medium"),
allowNull: true,
},
});
I tried to create an userInterface to replace any but it didn't work
interface userAttributes {
id: number;
username: string;
email: string;
password: string;
access_level: number;
biography: string;
profile_image: Blob;
}
Can you help me type the result of this findOne properly, please?
Upvotes: 1
Views: 3337
Reputation: 71
I found the solution reading sequelize doc: https://sequelize.org/docs/v6/other-topics/typescript/
the code in case anyone want to see:
import { CreationOptional, DataTypes, InferAttributes, InferCreationAttributes, Model } from "sequelize";
import { db } from "../database/db-connection";
class UserModel extends Model<InferAttributes<UserModel>, InferCreationAttributes<UserModel>> {
declare id: CreationOptional<number>;
declare username: string;
declare email: string;
declare password: string;
declare access_level: number;
declare biography: string;
declare profile_image: Blob | string;
declare createdAt: CreationOptional<Date>;
declare updatedAt: CreationOptional<Date>;
}
UserModel.init(
{
id: {
type: DataTypes.INTEGER,
autoIncrement: true,
allowNull: false,
primaryKey: true,
},
username: {
type: DataTypes.STRING,
allowNull: false,
},
email: {
type: DataTypes.STRING,
allowNull: false,
},
password: {
type: DataTypes.STRING,
allowNull: false,
},
access_level: {
type: DataTypes.INTEGER,
allowNull: false,
},
biography: {
type: DataTypes.STRING,
allowNull: true,
},
profile_image: {
type: DataTypes.BLOB("medium"),
allowNull: true,
},
createdAt: DataTypes.DATE,
updatedAt: DataTypes.DATE,
},
{
sequelize: db,
tableName: "users",
}
);
export { UserModel };
const user: UserModel | null = await UserModel.findOne({
where: {
id: id,
},
});
Upvotes: 3