Builder Pattern With Fluent Types
Implement a typed builder pattern with fluent interface and compile-time required field checking.
Code
export class QueryBuilder{private filters:Record<string,unknown>={};private sorts:string[]=[];private limit?:number;where(field:string,value:unknown):this{this.filters[field]=value;return this;}orderBy(field:string,dir:'ASC'|'DESC'='ASC'):this{this.sorts.push(field+' '+dir);return this;}take(n:number):this{this.limit=n;return this;}build(){return{where:this.filters,orderBy:this.sorts,limit:this.limit};}}export function query(){return new QueryBuilder();}What the code does
Count the class QueryBuilder and the function query as the entire surface area of Builder Pattern With Fluent Types.
The result comes back as an object carrying filters, sorts.
Using it
Import QueryBuilder from the file and call it — the rest of the code is implementation detail.
The call returns filters, sorts — destructure what you need at the call site.
Interactive Tools for This Topic
FAQ
- Does `QueryBuilder` modify its input?
- No mutation happens — the function reads its input and returns a new value.
- Can I paste this into a project as-is?
- Yes. Paste it in and run; no package manager step is needed. The file defines `query` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.