One of the new features in the latest versions of knex is a specific type that can now be directly imported from the library
Import { Knex } from 'knex'
This allows for proper typing of the knex instance object and enables the use of generics based on the database schema.
To define the type Knex
, you can alternatively use ReturnType<typeof knex>
to specify the instance.
Here's an example of how to use it:
import knex, { Knex } from 'knex';
const knexObj = knex({
client: 'sqlite3',
connection: {
filename: './data.db',
},
});
async function connDB(kInstance: Knex) {
await kInstance.schema
.createTable('users', (table) => {
table.increments('id');
table.string('user_name');
})
// ...and another
.createTable('accounts', (table) => {
table.increments('id');
table.string('account_name');
table.integer('user_id').unsigned().references('users.id');
});
}
connDB(knexObj);