Skip to main content

Overview

Drizzle’s custom type API allows you to create specialized column types that map between TypeScript types and database types. This is useful for:
  • Domain-specific types: Coordinates, currency, encrypted strings
  • Custom serialization: JSON with validation, compressed data
  • Type transformations: Automatic parsing and formatting
  • Database extensions: PostGIS, vector types, custom SQL types

Creating Custom Types

Basic Custom Type

Use the customType() function to define a new column type:

Type with Data Transformation

Map between JavaScript and database representations:

Type Parameters

Data Type

Define the TypeScript type for your column:

Driver Data Type

Specify the database driver’s representation:

Config Type

Add configuration parameters:

Real-World Examples

Currency Type

Handle monetary values with precision:

Date Range Type

PostgreSQL date ranges:

PostGIS Geography Type

Work with geospatial data:

Validated Email Type

Add validation during serialization:

UUID v7 Type

Implement UUID v7 with timestamp ordering:

Database-Specific Types

PostgreSQL

MySQL

SQLite

Advanced Patterns

Configurable Precision

NotNull by Default

With Validation Schema

Integrate with Zod or other validators:

Best Practices

1

Keep transformations simple

Complex logic should be in your application layer, not in type mappings.
2

Handle null values explicitly

Check for null in fromDriver and toDriver methods.
3

Use appropriate database types

Choose the database type that best matches your data semantics.
4

Validate in toDriver

Catch invalid data before it reaches the database.
5

Document your custom types

Add JSDoc comments explaining the type’s behavior and constraints.

Type Safety

Custom types maintain full TypeScript inference:
Export your custom types from a shared module to reuse them across multiple tables and maintain consistency.

Common Pitfalls

Avoid throwing errors in fromDriver as it will break queries. Return a safe default or handle errors gracefully.