TypeScript types vs runtime types
TypeScript types
Compile-time only. You define these for your tables and columns.
Runtime types
Actual JavaScript values returned by the database driver.
TypeScript types
In Kysely, you only define TypeScript types for your tables and columns. Since TypeScript is entirely a compile-time concept, TypeScript types cannot affect runtime JavaScript types.It’s up to you to select correct TypeScript types for your columns based on what the driver returns.
Runtime JavaScript types
The database driver (such aspg or mysql2) decides the runtime JavaScript types that queries return. Kysely never touches the runtime types the driver returns.
Kysely doesn’t modify data returned by the driver in any way — it simply executes the query and returns whatever the driver returns. An exception is when you use a plugin like
CamelCasePlugin, which changes column names.- Read the underlying driver’s documentation
- Figure out what the driver returns
- Align your TypeScript types to match
Configuring runtime JavaScript types
Most drivers provide ways to change the returned types. Here’s how to configure common scenarios:PostgreSQL
When using thepg driver, use the pg-types package to configure types.
Example: Return bigint as number
By default,pg returns bigint and numeric types as strings. Here’s how to configure it to return numbers:
MySQL
When using themysql2 driver, use the typeCast pool property.
Example: Map tinyint(1) to boolean
Type generators
Third-party type generators can automatically generate TypeScript types from your database schema:kysely-codegen
Generate types from your database schema
kanel-kysely
Another popular type generation tool
Common type mismatches
Here are some common scenarios where TypeScript types and runtime types might differ:| Database Type | Default Runtime Type | Common TypeScript Type | Notes |
|---|---|---|---|
PostgreSQL bigint | string | number | Configure with pg-types |
PostgreSQL numeric | string | number | Configure with pg-types |
MySQL tinyint(1) | number | boolean | Configure with typeCast |
PostgreSQL json | object | T | Automatically parsed |
SQLite json | string | T | Use ParseJSONResultsPlugin |
Best practices
Test your types
Always verify that runtime types match your TypeScript definitions by logging actual query results.
Configure driver early
Set up type parsing in your database configuration file before creating queries.
Document custom types
Comment your database type configuration so other developers understand the mappings.