Knex.js TypeScript Type Generator

0.5.0 · active · verified Wed Apr 22

Knex-types is an open-source utility module designed for Knex.js, focused on generating TypeScript definitions directly from a PostgreSQL database schema. Its primary purpose is to enhance type safety and developer experience when working with Knex.js by providing accurately typed database entities. The current stable version is 0.5.0, with minor feature updates and dependency upgrades released periodically, indicating an active maintenance and development cycle. Key differentiators include its tight integration with Knex.js, specific support for PostgreSQL features like `int2` arrays and `citext`, and options for schema inclusion/exclusion and custom prefixes/suffixes for generated files. It helps prevent runtime errors by catching schema-related type mismatches at compile-time, a common challenge in ORM-less database interactions.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize Knex and then use `knex-types` to generate TypeScript definition files from a PostgreSQL database schema, including common configuration options.

import KnexFactory, { Knex } from 'knex';
import { updateTypes } from 'knex-types';

// Assuming knexfile.ts exports a Knex configuration object
// Or you can directly define the config here
const knexConfig = {
  client: 'pg',
  connection: {
    host: process.env.DB_HOST ?? 'localhost',
    user: process.env.DB_USER ?? 'postgres',
    password: process.env.DB_PASSWORD ?? '',
    database: process.env.DB_NAME ?? 'mydatabase',
  },
};

const db: Knex = KnexFactory(knexConfig);

updateTypes(db, {
  output: './src/types/db.ts',
  schema: ['public'], // default schema to inspect
  exclude: ['knex_migrations', 'knex_migrations_lock'], // tables to ignore
  prefix: `// Generated by knex-types on ${new Date().toISOString()}\n`, // custom header
})
  .then(() => {
    console.log('TypeScript types generated successfully!');
    return db.destroy();
  })
  .catch((err) => {
    console.error('Error generating types:', err);
    return db.destroy().then(() => process.exit(1));
  });

view raw JSON →