Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoiding cyclic dependencies when using Sequelize with TypeScript

I wanted to create a proper setup with Sequelize and TypeScript but hit a roadblock. The official docs show all examples in the same file, thus they have no issues, but when I try to create models in separate files and reference them in the TS typings, I am hit with cyclic dependencies:

// User.ts

import { Guide } from '.';

export class User extends Model<InferAttributes<User>, InferCreationAttributes<User>> {
  declare id: CreationOptional<string>;
  // more attributes...

  declare guides?: NonAttribute<Guide>;
}

User.init(...);

// Guide.ts

import { User } from '.';

export class Guide extends Model<InferAttributes<Guide>, InferCreationAttributes<Guide>> {
  declare id: CreationOptional<string>;
  // more attributes

  declare author_id: NonAttribute<User['id']>;
  declare author?: NonAttribute<User>;

}

Guide.init(...);

As you can see, I need to reference Guide in User and vice-versa for correct typings. Am I missing something obvious? Is there a best-practice approach for this? There are also issues with calling association methods that stem from the problem above.

like image 440
IAmVisco Avatar asked Aug 16 '26 00:08

IAmVisco


1 Answers

Examples on https://sequelize.org/ are unhelpful and helpful at the same time. The way to do it is to have everything in the same file, or better, like it's described here

like image 159
aercolino Avatar answered Aug 22 '26 14:08

aercolino