Skip to content

Public Class Fields in examples #1736

Open
@mfvargo

Description

@mfvargo

Models in documentation will not function correctly due to Public Class Fields caveat in sequelize v6
https://sequelize.org/docs/v6/core-concepts/model-basics/#caveat-with-public-class-fields

Caveat with Public Class Fields
Adding a Public Class Field with the same name as one of the model's attribute is going to cause issues. Sequelize adds a getter & a setter for each attribute defined through Model.init. Adding a Public Class Field will shadow those getter and setters, blocking access to the model's actual data.

The models need a declare before the field name so the type can be specified without colliding with the inferred model getter/setter from the Sequelize base Model.

For example, in the Readme
https://github.com/sequelize/sequelize-typescript?tab=readme-ov-file#model-definition

it shows:

import { Table, Column, Model, HasMany } from 'sequelize-typescript';

@Table
class Person extends Model {
  @Column
  name: string;

  @Column
  birthday: Date;

  @HasMany(() => Hobby)
  hobbies: Hobby[];
}

But the defined fields are already part of the generated setters/getters for the sequelize Model, so to define the type returned without colliding with the internal fields there needs to be a declare such as:

import { Table, Column, Model, HasMany } from 'sequelize-typescript';

@Table
class Person extends Model {
  @Column
  declare name: string;

  @Column
  declare birthday: Date;

  @HasMany(() => Hobby)
  declare hobbies: Hobby[];
}

When updating my old project to the newer sequelize I hit this issue.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions