Knex.js TypeScript Type Generator
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
-
Error: Cannot find module 'knex' from 'knex-types'
cause The 'knex' package is a peer dependency of 'knex-types' and must be installed separately in your project.fixInstall Knex.js in your project: `npm install knex` (or `yarn add knex`). If you're using TypeScript, Knex ships its own types, so `@types/knex` is typically not needed. -
Property 'EntityRecord' does not exist on type '...'
cause The `EntityRecord` type was deprecated in `knex-types` v0.2.0 and replaced with `Knex.DbRecord<Entity>`.fixUpdate your type references from `EntityRecord<TableName>` to `Knex.DbRecord<TableName>` and ensure `import { Knex } from 'knex';` is present. -
SyntaxError: Named export 'knex' not found. The requested module 'knex' is a CommonJS module, which may not support named exports.
cause This error occurs when trying to `import { knex } from 'knex';` in an ES Module environment, as the main Knex factory function is primarily a default export in ESM contexts.fixChange your import statement for the Knex factory to `import KnexFactory from 'knex';`.
Warnings
- breaking Version 0.2.0 introduced a breaking change by deprecating the `EntityRecord` types. Developers should update their code to use `Knex.DbRecord<Entity>` instead for improved type consistency and adherence to Knex's own type definitions.
- gotcha `knex-types` is specifically designed for PostgreSQL databases. While Knex.js supports multiple databases, this library's schema introspection is tailored for PostgreSQL. Using it with other database systems will likely result in incorrect or incomplete type generation.
- gotcha The documentation and older examples often show `require()` syntax for both `knex` and `knex-types`. However, in modern TypeScript and ESM-first Node.js projects, `import` statements are preferred. Incorrect import styles (e.g., named import for the Knex factory) can lead to runtime errors.
Install
-
npm install knex-types -
yarn add knex-types -
pnpm add knex-types
Imports
- updateTypes
const { updateTypes } = require('knex-types');import { updateTypes } from 'knex-types'; - KnexFactory
import { knex } from 'knex';import KnexFactory from 'knex';
- Knex (Type)
import { Knex } from 'knex';
Quickstart
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));
});