Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
muslnode 18–226 runs
build_error
glibcnode 18–226 runs
build_error
Code
Verified usage
Verified import paths — ran on the pinned version, not inferred.
Product
✓ import { Product } from './dbschema';
✗ const Product = require('./dbschema').Product;
Output files are ESM modules, use `import` syntax. The path './dbschema' is an example, replace with your actual output file name.
TableTypes
✓ import { TableTypes } from './dbschema';
✗ import type { TableTypes } from 'pg-to-ts';
Interface containing a map of all table types. Imported from your generated schema file, not the `pg-to-ts` package itself.
tables
✓ import { tables } from './dbschema';
✗ import { product } from './dbschema';
A runtime constant object containing metadata for all tables, where individual table metadata (like `product`) is accessed as a property (e.g., `tables.product`).
Demonstrates how to generate TypeScript types from a PostgreSQL schema using `pg-to-ts`, then use these generated types and runtime constants with `node-postgres` to insert and query data safely. Note: requires `pg` installed.
import { Pool } from 'pg';
import { Product, ProductInput, tables } from './dbschema'; // Assuming this is your generated file
// Step 1: Generate your schema file (dbschema.ts)
// Run this command once after database schema changes:
// npm install pg-to-ts
// pg-to-ts generate -c "postgresql://user:password@host:5432/mydb" -o ./dbschema.ts
// For this example, we assume dbschema.ts has already been generated based on a 'product' table:
/*
// Example content of dbschema.ts:
export interface Product {
id: string;
name: string;
description: string;
created_at: Date;
}
export interface ProductInput {
id?: string;
name: string;
description: string;
created_at?: Date;
}
const product = {
tableName: 'product',
columns: ['id', 'name', 'description', 'created_at'],
requiredForInsert: ['name', 'description'],
} as const;
export const tables = {
product
};
*/
async function main() {
// Step 2: Use the generated types in your application
const connectionString = process.env.DATABASE_URL ?? 'postgresql://user:pass@localhost:5432/mydb';
const pool = new Pool({ connectionString });
try {
const newProduct: ProductInput = {
name: 'Example Product',
description: 'A product generated by pg-to-ts quickstart.'
};
// Use runtime constants for query construction, ensuring type safety
const insertColumns = tables.product.requiredForInsert.join(', ');
const placeholders = tables.product.requiredForInsert.map((_, i) => `$${i + 1}`).join(', ');
const insertValues = tables.product.requiredForInsert.map(key => newProduct[key]);
const insertRes = await pool.query<Product>(
`INSERT INTO ${tables.product.tableName} (${insertColumns}) VALUES (${placeholders}) RETURNING *`,
insertValues
);
const createdProduct = insertRes.rows[0];
console.log('Created product:', createdProduct);
// Fetch all products using the generated type
const selectRes = await pool.query<Product>(`SELECT * FROM ${tables.product.tableName}`);
const products: Product[] = selectRes.rows;
console.log('All products:', products.map(p => p.name));
} catch (error) {
console.error('Database operation failed:', error);
} finally {
await pool.end();
}
}
main();
pg-to-ts --version
Errors
Common errors & fixes
Property 'name' is missing in type '{ id: string; description: string; }' but required in type 'ProductInput'.
Attempting to create a record without providing all non-nullable, non-defaulted columns required for insertion (as defined by the generated `TableInput` interface, e.g., `ProductInput`).
fixEnsure all properties listed in the generated `TableInput` interface that are not marked as optional (`?`) are provided when inserting new records. Check the `requiredForInsert` property on the generated runtime `table` object for clarity.
Type 'Date' is not assignable to type 'string'.
This error occurs when the generated schema uses `string` for date/timestamp columns (due to `--datesAsStrings`), but the database driver (e.g., `node-postgres`) is returning `Date` objects.
fixEither remove the `--datesAsStrings` flag during generation to use `Date` objects in your types, or configure your database driver's type parsers to serialize date/timestamp columns as ISO 8601 strings to match the generated types.
Property 'metadata' does not exist on type 'Product'. Did you mean 'name'?
Trying to access a JSON/JSONB column without configuring `pg-to-ts` to use a specific TypeScript type for it, resulting in the column being typed as `unknown` (which might not be explicitly reflected as a property) or a less precise type.
fixAdd a JSDoc `@type` comment to the JSON column in your SQL schema (e.g., `COMMENT ON COLUMN product.metadata IS '@type {ProductMetadata}'`) and use the `--jsonTypesFile './path/to/my-db-types'` option when generating your schema file. Audit
Dependencies
typescriptrequiredRequired peer dependency for TypeScript compilation and understanding generated types.
pgoptionalCommonly used for interacting with PostgreSQL databases in Node.js applications that consume the generated types and runtime constants.