kriasoft / knex-types

Generate TypeScript definitions (types) from a PostgreSQL database schema.
MIT License
63 stars 21 forks source link

How to use it properly? #25

Open vencho-mdp opened 1 year ago

vencho-mdp commented 1 year ago

Hi! In the readme is shown clearly how this library can generate types, but how do we use them to incorporate them into our app?

snipd-mikel commented 1 year ago

I have done the following to have the types available when using knex, based on this Stackoverflow answer: https://stackoverflow.com/questions/67034024/knex-js-table-infered-typescript-types

Create a directory for your custom types, (i did src/@types) an add all your .d.ts (also should work with standar .ts)

Then, in your tsconfig.ts add the following inside compilerOptions

"typeRoots": ["./nodemodules/@types", "./src/@types"]

then inside your custom types directory create you declaration file for knex Tables, in my case src/@types/index.d.ts

import * as db from './generated/db';

declare module 'knex/types/tables' {      
  interface Tables extends TablesType {
  }
}

type TablesType = {
  [table in keyof db.Tables]: db.Tables[table];
}
vencho-mdp commented 1 year ago

Hey! Thank you for answering @snipd-mikel ! Just with that all the autocompletions should be working? How would you generate those types automatically?

snipd-mikel commented 1 year ago

Hi @vencho-mdp. After using that fix, the typings for simple select, insert and update statements work fine.