Web Development
TypeScript
Subjective
Oct 04, 2025
How do you create a type-safe ORM query builder?
Detailed Explanation
Use mapped types for table schemas, conditional types for query validation, and method chaining with type narrowing.
Basic Schema Definition:
type User = {
id: number;
name: string;
email: string;
age: number;
};
type Post = {
id: number;
title: string;
content: string;
userId: number;
};
Query Builder Implementation:
type WhereClause = {
[K in keyof T]?: T[K] | { gt: T[K] } | { lt: T[K] } | { in: T[K][] };
};
type SelectFields = (keyof T)[];
class QueryBuilder {
constructor(private tableName: string) {}
select(...fields: K[]): QueryBuilder {
// Implementation
return new QueryBuilder(this.tableName);
}
where(conditions: WhereClause): QueryBuilder {
// Implementation
return this;
}
execute(): Promise[]> {
// Implementation
return Promise.resolve([]);
}
}
// Usage
const userQuery = new QueryBuilder('users')
.select('id', 'name', 'email')
.where({ age: { gt: 18 } })
.execute(); // Returns Promise[]>
Advanced Join Support:
type JoinResult = T & U;
class AdvancedQueryBuilder {
constructor(private tableName: string) {}
join(
table: string,
leftKey: K,
rightKey: L
): AdvancedQueryBuilder> {
// Implementation
return new AdvancedQueryBuilder>(this.tableName);
}
select(...fields: K[]): AdvancedQueryBuilder> {
// Implementation
return new AdvancedQueryBuilder>(this.tableName);
}
}
// Usage with joins
const joinQuery = new AdvancedQueryBuilder('users')
.join('posts', 'id', 'userId')
.select('name', 'title'); // Type: Pick
Benefits:
• Compile-time validation of table schemas
• Type-safe field selection
• Prevents invalid join conditions
• Excellent IDE autocomplete for database operations.
Discussion (0)
No comments yet. Be the first to share your thoughts!
Share Your Thoughts