Ken Yip
Ken Yip

Reputation: 761

How to use knex object as type?

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?

Upvotes: 1

Views: 1764

Answers (2)

Besnik Kor&#231;a
Besnik Kor&#231;a

Reputation: 1094

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

Upvotes: 2

tenshi
tenshi

Reputation: 26324

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

Upvotes: 3

Related Questions