Throughout this series, we’ve built up a serious toolkit:
- Custom Type Guards to validate unknown data at runtime.
- Discriminated Unions to eliminate impossible states.
- Generics, Mapped Types, and Conditional Types to transform existing shapes.
- Template Literal Types to parse and enforce string structures at compile time.
Now, let's combine these techniques to solve a classic engineering problem: How do you design an ergonomic, fluent API where TypeScript infers complex types automatically—and prevents developers from calling methods out of order?
To do that, we need to understand two behind-the-scenes mechanisms: Type Inference and Variance, and apply them to build a Type-Safe Query Builder.
1. Controlling Type Inference (NoInfer<T>)
TypeScript is great at inferring generic types from function arguments—sometimes too great. Consider a function that checks if a value is in a list of allowed defaults:
function createConfig<T>(allowed: T[], defaultValue: T) {
return { allowed, defaultValue };
}
// ❌ Problem: Instead of throwing an error, TypeScript widens T to "dark" | "light" | "blue"!
const config = createConfig(["dark", "light"], "blue");
Because T appears in both parameters, TypeScript creates a union of all inputs rather than flagging "blue" as invalid.
To fix this, TypeScript provides the built-in NoInfer<T> utility type. It tells the compiler: "Infer T from the other arguments first, then strictly check this argument against that inferred type."
function createConfig<T>(allowed: T[], defaultValue: NoInfer<T>) {
return { allowed, defaultValue };
}
// ✅ Compile Error: Argument of type '"blue"' is not assignable to parameter of type '"dark" | "light"'
const config = createConfig(["dark", "light"], "blue");
2. Understanding Variance (in and out)
When working with generics, variance describes how subtyping between complex types relates to subtyping between their components.
Suppose Admin extends User:
-
Covariance (
out): A container ofAdmins can be used where a container ofUsers is expected (e.g.,readonly Admin[]is assignable toreadonly User[]). You are producing (outputting) values. -
Contravariance (
in): A function accepting aUsercan be used where a function accepting anAdminis expected (e.g.,(u: User) => voidis assignable to(a: Admin) => void). You are consuming (inputting) values.
In complex recursive types, TypeScript can occasionally miscalculate or struggle with the performance of variance checks. You can make your intent explicit using in and out modifiers:
// Explicit variance annotations improve compiler speed and catch subtle type bugs
interface Producer<out T> {
make(): T;
}
interface Consumer<in T> {
consume(item: T): void;
}
3. Real-World Power: The Type-State Builder Pattern
Let's combine Generics, this Parameter Constraints, and Type-State Tracking to build a fluent SQL-like query builder where:
- You cannot call
.execute()before calling.from(). -
.select()only autocompletes columns that exist on the chosen table. - The final return type of
.execute()contains only the columns you selected.
Step 1: Define Our Schema
interface DatabaseSchema {
users: { id: string; email: string; role: "admin" | "member" };
posts: { id: string; title: string; published: boolean };
}
Step 2: Track State in Generic Parameters
Instead of mutating a class blindly, each method in our builder returns a new typed representation of the builder with updated generic parameters:
class QueryBuilder<
Table extends keyof DatabaseSchema | null = null,
Selected extends keyof any = never
> {
private tableName?: string;
private selectedFields: string[] = [];
// 1. Set the table and lock in the 'Table' generic
from<T extends keyof DatabaseSchema>(table: T): QueryBuilder<T, never> {
const next = new QueryBuilder<T, never>();
next.tableName = table;
return next;
}
// 2. Constrain 'K' to keys of the chosen 'Table'
select<K extends keyof DatabaseSchema[NonNullable<Table>]>(
...fields: K[]
): QueryBuilder<Table, Selected | K> {
const next = new QueryBuilder<Table, Selected | K>();
next.tableName = this.tableName;
next.selectedFields = fields as string[];
return next;
}
// 3. Only allow execution if a Table is selected (using 'this' parameter constraint)
execute<T extends keyof DatabaseSchema>(
this: QueryBuilder<T, Selected>
): Array<Pick<DatabaseSchema[T], Extract<Selected, keyof DatabaseSchema[T]>>> {
console.log(`SELECT ${this.selectedFields.join(", ")} FROM ${this.tableName}`);
return [] as any; // Runtime execution logic goes here
}
}
Step 3: Seeing It in Action
Look at the developer experience and compile-time guardrails we just unlocked:
const db = new QueryBuilder();
// ❌ Compile Error: The 'this' context of type 'QueryBuilder<null, never>' is not assignable...
db.execute();
// ❌ Compile Error: Argument of type '"title"' is not assignable to '"id" | "email" | "role"'
db.from("users").select("title");
// ✅ Valid! Autocompletes table names, then autocompletes ONLY "users" columns
const results = db
.from("users")
.select("id", "email")
.execute();
// Type of `results` is automatically inferred as:
// Array<{ id: string; email: string }> 🎉
Wrapping Up
By combining type-state generics, this parameter constraints, and Pick, we turned a runtime query string into a guided, self-documenting API where invalid states are impossible to write.
When we treat TypeScript's type system as a state machine rather than just a set of interfaces, your editor stops being a passive text box and becomes an active pair programmer.
Top comments (0)