Write SQL in TypeScript and get exact types for rows and parameters. TypeSQL parses your SQL inside the type checker: no codegen, no database connection, no build step.
TypeSQL supports PostgreSQL, SQLite, MySQL and MariaDB. The @typesql/core runtime is tiny (under 3 kB minified and gzipped) and has no dependencies.
TypeSQL checks queries against a DB type that describes your tables. Derive it from your migrations, generate it from a live database, or take it from Kysely, Drizzle or Prisma.
You can also write it by hand with your database's type names.
Create sql from your driver's client, import the schema and run SQL against it:
import { Pool } from "pg";
import { createSql } from "@typesql/pg";
import type { DB } from "./db/schema";
const sql = createSql<DB>(new Pool());
// rows is { email: string; title: string | null }[]: the LEFT JOIN makes title nullable.
// sql.param() sends userId as a parameter, typed like u.id, so it must be a number.
const rows = await sql(
`SELECT u.email, p.title
FROM users u LEFT JOIN posts p ON p.author_id = u.id
WHERE u.id = ${sql.param(userId)}`,
).execute();
// Compile error: column "emial" does not exist. Perhaps you meant the column "email"?
sql("SELECT emial FROM users");@typesql/postgres works the same way with postgres.js, @typesql/sqlite with node:sqlite, better-sqlite3 and bun:sqlite, and @typesql/mysql with mysql2, the mariadb connector, PlanetScale and TiDB Cloud; see SQLite and MySQL and MariaDB.
Every TypeScript editor shows a query's row type on hover and underlines mistakes in the SQL. The TypeSQL extension for VS Code (Marketplace, Open VSX) adds table and column completions and syntax highlighting inside sql() strings. See VS Code and Neovim.
The full guide is at typesql.karsli.net. It covers the SQL TypeSQL supports, parameters and fragments, writing data, and known limits. Upgrading? See the upgrade guide and the changelog.
