前置知识: TypeScript

类型安全的数据库查询

00:00
1 min Advanced 2026/6/14

构建类型安全的查询构建器

1. 模式定义

interface Schema {
  users: {
    id: number;
    name: string;
    email: string;
    age: number;
  };
  posts: {
    id: number;
    title: string;
    content: string;
    userId: number;
    createdAt: Date;
  };
}

2. 查询构建器

class QueryBuilder<T extends keyof Schema, S extends Schema> {
  private wheres: string[] = [];
  private selectFields: (keyof S[T])[] = [];

  constructor(private table: T) {}

  select<K extends keyof S[T]>(...fields: K[]): QueryBuilder<T, S> {
    this.selectFields = fields;
    return this;
  }

  where<K extends keyof S[T]>(field: K, op: string, value: S[T][K]): this {
    this.wheres.push(`${String(field)} ${op} ?`);
    return this;
  }

  async execute(): Promise<Pick<S[T], (typeof this.selectFields)[number]>[]> {
    // 实现查询逻辑
    return [] as any;
  }
}

// 使用
const users = await new QueryBuilder<'users', Schema>('users')
  .select('id', 'name')
  .where('age', '>', 18)
  .execute();

知识检测

学习进度

-- 已学文档
--% 知识覆盖率

学习推荐

专注模式