Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Knex typescript fails with joins #5375

Open
aliosman21 opened this issue Nov 9, 2022 · 3 comments
Open

Knex typescript fails with joins #5375

aliosman21 opened this issue Nov 9, 2022 · 3 comments

Comments

@aliosman21
Copy link

aliosman21 commented Nov 9, 2022

Environment

Knex version: 2.0.0
Postgres+ 12.11:
OS: Windows

Questions about how to use knex

I am trying to use Knex and inspect the types of the result so for instance

const entries = await trx<Table_Type>('table')
			.select(
				trx.ref('id').withSchema('table'),
				trx.ref('name').withSchema('table'),
			)

The entries type is correct for each column selected.

But once I try to make a join like this

.leftJoin<Table2_Type>('table2', 'table.id', 'table2.table1_id')

All types are marked as never, am I missing something ?

@aliosman21 aliosman21 changed the title # Environment Knex typescript fails with joins Nov 9, 2022
@joshkel
Copy link

joshkel commented Nov 10, 2022

Are you augmenting the Table interface, as described at https://knexjs.org/guide/#typescript?

The type definitions, overloads, and inferences necessary to make leftJoin work are quite complicated, and manually specifying a type as in .leftJoin<Table2_Type> may confuse it. However, if you augment the Table interface and let TypeScript + Knex infer the appropriate generic types itself, it ought to work. (At least, it does for my project.)

@aliosman21
Copy link
Author

Yes, I do augment the table interface with all new tables.

Just note my original query is quite a lengthy one with multiple joins, for a few joins type is inferred correctly but after some more joins it just doesn't infer it anymore.

@owlas
Copy link

owlas commented Mar 1, 2023

I've also noticed the types change depending on the order of the columns in the join ON clause:

await knex('a').innerJoin('b', 'a.id', 'b.id')
// type is (A & B)

await ('a').innerJoin('b', 'b.id', 'a.id')
// type is (A | (A & B))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants