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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With