0Pricing
TypeScript Academy · Lesson

Designing a Fluent Query DSL

Build a chainable, self-validating query API.

Designing a Fluent Query DSL is a free TypeScript Academy lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the TypeScript Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Designing a Fluent Query DSL

We design a chainable query DSL where each step refines the allowed next steps via return types. The result reads like SQL and rejects invalid orderings at compile time.

The Target Grammar

We want: from then optional where (repeatable) then a terminal select. You cannot select before from, and you cannot from twice.

State Interfaces

Model each stage as an interface returning the next stage.

interface Builder {
  from(table: string): FromStage;
}
interface FromStage {
  where(cond: string): FromStage; // repeatable
  select(...cols: string[]): Result;
}
interface Result { sql: string; }

Enforcing Order

Because select only exists on FromStage, calling it on the initial Builder is a compile error. Order is enforced purely by which methods each stage exposes.

declare const db: Builder;
db.from("users").select("id"); // ok
db.select("id");               // Error: select missing on Builder

Tracking Selected Columns

Add a phantom generic to remember which columns were selected, so the result type is precise.

interface FromStage<T extends string = never> {
  where(c: string): FromStage<T>;
  select<C extends string>(...cols: C[]): Result<C>;
}
interface Result<C extends string> { columns: C[]; }

Refining With Each Call

Each where can accumulate constraints in the type too. Here we keep it simple, but the pattern generalizes to track bound parameters.

const q = db.from("users").where("age > 18").where("active = true");
// still FromStage; select remains available

Preventing Repeated from

Since FromStage does not expose from, you cannot call it twice. The grammar forbids it structurally, no runtime guard needed.

db.from("a").from("b"); // Error: from does not exist on FromStage

A Terminal Step

select returns Result, which exposes neither where nor from, terminating the chain. Only result-reading operations remain.

const r = db.from("users").select("id", "name");
r.columns; // ("id" | "name")[]
// r.where(...) -> Error: where not on Result

Typed Column Constraints

Constrain columns to a known table schema with another generic, so unknown columns are rejected, blending this DSL with the earlier ORM ideas.

interface Table<Cols extends string> {
  select<C extends Cols>(...cols: C[]): Result<C>;
}
// db.from gives Table<"id" | "name" | "age">

Optional vs Required Steps

Make a step required by only exposing the next method after it. For example, force at least one where by returning a stage whose select appears only after where is called. The same chained types can also infer the result row type of executing the query, tying compile-time grammar to runtime data.

Why This Matters

A fluent DSL designed this way is self-documenting and impossible to misuse: autocomplete shows only valid next steps, and illegal sequences never compile. This is the backbone of ergonomic builder libraries.

Quick Check

Confirm your understanding of fluent DSL design.

Recap

You designed a fluent query DSL as a type-level state machine: each stage interface returns the next, exposing only valid methods. Phantom generics track selected columns, terminal stages end the chain, and column constraints reject unknown names, all enforced by return types.

Frequently asked questions

Is the “Designing a Fluent Query DSL” lesson free?

Yes — the full text of “Designing a Fluent Query DSL” is free to read here on the web, and the TypeScript Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the TypeScript Academy course, upgrade to CoddyKit PRO.

What will I learn in “Designing a Fluent Query DSL”?

Build a chainable, self-validating query API. You practise TypeScript Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start TypeScript Academy?

No prior experience is required. TypeScript Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Designing a Fluent Query DSL” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this TypeScript Academy lesson?

Yes. Every TypeScript Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. What Is a Type-Level DSL
  2. Designing a Fluent Query DSL
  3. Compile-Time Input Validation
  4. Error Messages in Type-Level DSLs
← Back to TypeScript Academy