typescriptpostgresqlsequelize.js

TypeScript complains when I define a Sequelize model with an id, but don't provide an id when calling Model.create()


I'm using the class style model declaration:

export class Supplier extends Model<InferAttributes<Supplier>, InferCreationAttributes<Supplier>> {
  declare id: number
  declare companyName: string | null
  declare website: string | null
  declare contactName: string | null
  declare contactEmail: string | null
  declare contactPhone: string | null
  declare country: string | null
}

Supplier.init(
  {
    id: {
      type: DataTypes.INTEGER,
      autoIncrement: true,
      primaryKey: true,
    },
    companyName: {
      type: DataTypes.STRING,
      allowNull: true,
    },
    // ...

Then, to create a new Supplier row:

await Supplier.create({
  companyName: form.companyName,
  website: form.website,
  contactName: form.contactName,
  contactEmail: form.contactEmail,
  contactPhone: form.contactPhone,
  country: form.country,
})

And I get Property 'id' is missing in type from TypeScript. If I do declare id?: number the error goes away, but somehow it doesn't feel right, because the ID is not really optional. What is the correct way to make the TS error go away?


Solution

  • You should use the "CreationOptional" utility type that sequelize provides in order to create and save a new model instance without providing the defined model field, which in this case is "id".


    That would be defined as declare id: CreationOptional<number>;. This infers it as a persistence attribute and marks it as an optional creation attribute.