Menu

TypeSQL: type-safe plain SQL in TypeScript
📰

TypeSQL: type-safe plain SQL in TypeScript

DEV Community: postgres·İsmail Karslı·17 days ago
#ujNu601r
#devtopostgresql#devto#dev#type#typesql
Reading 0:00
15s threshold

I like writing SQL. But in TypeScript, raw SQL usually means giving up types: you get any[] back, or you write the row type by hand and hope it stays in sync with the query.

So I built TypeSQL . It checks your SQL strings with the TypeScript compiler and gives you exact types for rows and parameters.

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 (); // rows: { email: string; title: string | null }[]

Enter fullscreen mode

Exit fullscreen mode

title is string | null because of the LEFT JOIN . userId must be a number, because it's compared to u.id . Nobody wrote those types: the compiler worked them out from the SQL.

How it works

TypeSQL is a SQL parser written in TypeScript's type system. When you call sql("…") with a string literal, the compiler parses the SQL and looks up each table and column in your schema type. This happens in your editor and in tsc .

At runtime, sql() does very little.…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.