sequelize-typescript icon indicating copy to clipboard operation
sequelize-typescript copied to clipboard

Alternate model definition proposal

Open michan85 opened this issue 4 years ago • 1 comments

Hello,

I managed to reduce a bit of boiler plate with a simple type definition:

export type ModelAttrs<T> = Omit<T,  keyof Model>

// example

// not required
export interface BaseModelAttrs{
  id: number
  createdAt: Date;
  updatedAt: Date;
}

export type ModelAttrs<T> = Omit<T,  keyof Model> & BaseModelAttrs

export default class BaseModel<T> extends Model<ModelAttrs<T>, Partial<ModelAttrs<T>>>{}

@Table
class Person extends BaseModel<Person> {
  @Column
  name!: string

  @Column
  birthday!: Date
}

this gives the proper auto complete when creating a new instance:

Screenshot 2021-05-13 at 11 50 01

without the attrs you get all the model props

Screenshot 2021-05-13 at 11 52 27

unfortunately this requires a base class to work

Screenshot 2021-05-13 at 11 53 54

Im not exactly sure how this could be best integrated into the library (if at all) but here are some options. Im happy to pr them but just wanted to get your feelings first.

Options:

  • docs: just a some docs and people can copy and paste the snippets
  • TypedModel base class
export abstract class TypedModel<T,C=T> extends Model<ModelAttrs<T>,ModelAttrs<C>>{}

michan85 avatar May 13 '21 10:05 michan85

This has actually been improved recently in Sequelize, and can be used in sequelize-typescript too, see InferAttributes & InferCreationAttributes here https://sequelize.org/docs/v6/other-topics/typescript/

It should get even better in a future major release: https://github.com/sequelize/sequelize/pull/14091

ephys avatar Apr 07 '22 13:04 ephys