Skip to main content

Type Signature

type ColumnType<
  SelectType,
  InsertType = SelectType,
  UpdateType = SelectType,
> = {
  readonly __select__: SelectType
  readonly __insert__: InsertType
  readonly __update__: UpdateType
}

Overview

ColumnType allows you to specify different types for select, insert, and update operations on a database column. This is particularly useful for:
  • Database-generated columns (IDs, timestamps)
  • Columns with different input/output formats (dates as strings for insert, Date objects for select)
  • Read-only columns that can’t be inserted or updated

Type Parameters

SelectType
type
required
The TypeScript type returned when selecting this column from the database.
InsertType
type
default:"SelectType"
The TypeScript type accepted when inserting this column. Defaults to SelectType if not specified.
UpdateType
type
default:"SelectType"
The TypeScript type accepted when updating this column. Defaults to SelectType if not specified.

Examples

Database-Generated Column

Make a column optional in inserts and updates (useful for auto-incrementing IDs):
interface PersonTable {
  id: ColumnType<number, number | undefined, number>
  name: string
}
The Generated<T> type is a shortcut for this pattern.

Read-Only Column

Prevent insertion and update of a column:
interface PersonTable {
  id: ColumnType<number, never, never>
  name: string
}
The GeneratedAlways<T> type is a shortcut for this pattern.

Different Types Per Operation

Accept strings for insert, but prevent updates and return Date objects for selects:
interface PersonTable {
  id: Generated<number>
  created_at: ColumnType<Date, string, never>
  name: string
}
With this definition:
// Insert accepts string
await db.insertInto('person')
  .values({
    created_at: '2024-01-01',
    name: 'John'
  })
  .execute()

// Select returns Date
const person = await db
  .selectFrom('person')
  .selectAll()
  .executeTakeFirst()
// person.created_at is Date

// Update doesn't allow created_at
await db.updateTable('person')
  .set({
    created_at: '2024-01-02' // Type error!
  })
  .execute()

Source

View source on GitHub

Build docs developers (and LLMs) love