There are two simple models in a 1:N relationship - one student has many tasks.
// StudentModel.ts
interface StudentI extends Model<InferAttributes<StudentI>, InferCreationAttributes<StudentI>> {
id: CreationOptional<number>
name: string
age: number
}
const StudentModel = sequelizeConn.define<StudentI>("student", {
id: {
type: DataTypes.INTEGER,
autoIncrement: true,
primaryKey: true
},
name: {
type: DataTypes.STRING(64),
allowNull: false
},
age: {
type: DataTypes.INTEGER,
allowNull: false
}
})
export default StudentModel
// TaksModel.ts
interface TaskI extends Model<InferAttributes<TaskI>, InferCreationAttributes<TaskI>> {
id: CreationOptional<number>,
student_id: number,
definition: string
}
const TaksModel = sequelizeConn.define<TaskI>("task", {
id: {
type: DataTypes.INTEGER,
autoIncrement: true,
primaryKey: true
},
student_id: {
type: DataTypes.INTEGER,
allowNull: false
},
definition: {
type: DataTypes.STRING(64),
allowNull: false
}
})
export default TaksModel
// associations.ts
StudentModel.hasMany(TaksModel, { foreignKey: "student_id", as: "tasks" })
TaksModel.belongsTo(StudentModel, { foreignKey: "student_id", as: "student" })
The types of the models work fine on their own, but when dealing with relationships, the use of the "any" keyword becomes necessary.
randomFile.ts
const task = await TaksModel.findOne({
where: {
id: 1
},
include: [
{
model: StudentModel,
as: "student"
}
]
})
// if (task.student.age == 15 ) { } -> return Property 'student' does not exist on type 'TaskI'
if ((task as any).student.age == 15 ) { //do some stuff }
Does anyone have a better example of how to avoid using the "any" keyword? The official documentation mainly covers the types of models themselves rather than their associations.