Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I correctly type Sequelize JOINs using TypeScript?

I'm trying to JOIN two tables together in Sequelize:

const results = await MainModel.findAll({ include: [ JoinedModel ] });

However, TypeScript (in --strict mode, at least) complains when I try to access data from the joined table:

const joinedField = results[0].joinedModel.joinedField;

which results in:

Property 'joinedModel' does not exist on type 'Instance<MainModelAttributes>'.

Despite TypeScript's complaint, the above code does actually provide me with the value in the joined field.

What is the correct way to type this? (And am I using Sequelize correctly here?)

like image 970
Vincent Avatar asked Feb 17 '26 12:02

Vincent


1 Answers

You can cast the result in this manner.

const results = await MainModel.findAll({ include: [ JoinedModel ] }) as Array<MainModel & {JoinedModel: JoinedModel}>;
like image 57
Krishan V Avatar answered Feb 20 '26 07:02

Krishan V



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!