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:
types.d.ts file added to compilerOptions.types in tsconfig.jsonDid anyone get to make it work? What am I missing ?
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
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