Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

knex.js: Table Infered TypeScript types

I am playing with knex.js and I want to try TypeScript support for my tables.

Following this http://knexjs.org/#typescript-support

I have tried to add this simple snippet everywhere with no results.

declare module 'knex/types/tables' {
 interface Tables {
    // This is same as specifying `knex<User>('users')`
    users: { id: string, name: string };
}

I've tried:

  • on top of the same file that perform query
  • on a types.d.ts file added to compilerOptions.types in tsconfig.json

Did anyone get to make it work? What am I missing ?

like image 432
Claudio Avatar asked Oct 27 '25 00:10

Claudio


1 Answers

I've got this to work with the following:

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 { knex } from 'knex';

import { User } from 'path/to/your/interfaces'

declare module 'knex/types/tables' {      
  interface Tables {
    users: User;
    users_composite: Knex.CompositeTableType<
      User,
      Pick<User, 'name'> & Partial<Pick<User, 'created_at' | 'updated_at'>>,
      Partial<Omit<User, 'id'>>
    >;
  }
}

Note: this is just the same example from official knex, please see for more information

Then you can use infered types:

const user = await db.from('users').first() // User || undefined
const user = await db.table('users').first() // User || undefined

...Just for make it clear my db variable is just exported somewhere else as knex({...}), see

like image 129
Erik Fernando Loaiza Patiño Avatar answered Oct 28 '25 16:10

Erik Fernando Loaiza Patiño