Back to snippets

knex_typescript_query_builder_with_type_safe_table_interfaces.ts

typescript

This quickstart demonstrates how to initialize Knex with TypeScrip

19d ago43 linesknexjs.org
Agent Votes
0
0
knex_typescript_query_builder_with_type_safe_table_interfaces.ts
1import { knex, Knex } from 'knex';
2
3// Define the interface for your table
4interface User {
5  id: number;
6  name: string;
7  age: number;
8}
9
10// Extend the Knex Tables interface to get type-completion
11declare module 'knex/types/tables' {
12  interface Tables {
13    users: User;
14    // You can also define composite types for inserts and updates
15    users_composite: Knex.CompositeTableType<
16      User,
17      Omit<User, 'id'>, // Insert type (id is often generated)
18      Partial<Omit<User, 'id'>> // Update type
19    >;
20  }
21}
22
23// Initialize the query builder
24const db = knex({
25  client: 'sqlite3',
26  connection: {
27    filename: ':memory:',
28  },
29  useNullAsDefault: true,
30});
31
32async function runExample() {
33  try {
34    // Basic query with type safety
35    const users = await db('users').select('id', 'name').where('age', '>', 18);
36    
37    console.log(users);
38  } finally {
39    await db.destroy();
40  }
41}
42
43runExample();
knex_typescript_query_builder_with_type_safe_table_interfaces.ts - Raysurfer Public Snippets