Home > OS >  How to use knex object as type?
How to use knex object as type?

Time:11-05

I would like to write a function that accepts the knex instance as a parameter.

I try to do that by

import knex from "knex";
export async function createTestTable(_knex: ReturnType<knex>) {
    ... 
}

But it returns the Cannot use namespace 'knex' as a type.ts(2709) error. Is there any method I can do the correct type annotation?

CodePudding user response:

You can use typeof to get the type of knex, the value. It's currently being confused for the namespace.

import knex from "knex";

export async function createTestTable(_knex: ReturnType<typeof knex>) {
    
}

Playground

CodePudding user response:

In newer versions of knex there's a type that can be imported from the library

Import { Knex } from 'knex'

This can be used to correctly type the knex instance obj and additionally generics can be provided to it based on the db schema.

The equivalent of the type Knex would be ReturnType<typeof knex> so you can use it like that as well to type the instance.

sample usage:

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);

  • Related