Skip to content

类型-Safe Builder 模式

中等 约 25 分钟

你将构建什么

QueryBuilder 那个 uses 方法 chaining 到构建查询对象. 每个方法返回 builder for chaining, and 构建() 方法返回最终输入查询.

学习目标

  • Implement fluent builder 模式
  • Use 方法 chaining 使用返回类型
  • 构建复杂对象步骤通过步骤
  • Apply generics 到类-based 模式

前置要求

  • 类
  • Generics
  • 方法 chaining

步骤

  1. 1

    定义查询类型

    创建接口 for 查询部分: 筛选, 排序, and pagination. 最终查询组合它们.

    代码
    interface Filter { field: string; op: string; value: unknown; }
    interface Query { table: string; filters: Filter[]; limit?: number; sort?: string; }

    预期结果

    查询 and 筛选接口是 定义.

  2. 2

    编写 builder 类

    创建 QueryBuilder 类使用 fluent 方法. 每个方法返回 这个 for chaining. 构建方法返回最终查询.

    代码
    class QueryBuilder {
      private query: Partial<Query> = { filters: [] };
      table(name: string): this { this.query.table = name; return this; }
      where(field: string, op: string, value: unknown): this {
        this.query.filters!.push({ field, op, value }); return this;
      }
      limit(n: number): this { this.query.limit = n; return this; }
      sortBy(field: string): this { this.query.sort = field; return this; }
      build(): Query {
        if (!this.query.table) throw new Error("Table is required");
        return this.query as Query;
      }
    }

    预期结果

    fluent builder 那个 constructs 查询步骤通过步骤.

  3. 3

    Use builder

    链方法到 构建查询. fluent API 读取 naturally and result 是 fully 输入.

    代码
    const q = new QueryBuilder()
      .table("users")
      .where("age", ">", 18)
      .where("active", "=", true)
      .sortBy("name")
      .limit(10)
      .build();
    console.log(q); // { table: "users", filters: [...], limit: 10, sort: "name" }

    预期结果

    fully constructed, 输入查询对象构建通过 fluent chaining.

  4. 4

    添加类型守卫与运行时检查

    编写类型守卫函数(user-defined type guard)在运行时验证数据形状,结合 unknown 类型安全处理外部输入。类型守卫让 TypeScript 在运行时也有类型安全。

    代码
    type User = { id: number; name: string };
    
    function isUser(value: unknown): value is User {
      if (typeof value !== "object" || value === null) return false;
      const obj = value as Record<string, unknown>;
      return typeof obj.id === "number" && typeof obj.name === "string";
    }
    
    // Usage with unknown input
    const data: unknown = JSON.parse(rawJson);
    if (isUser(data)) {
      console.log(data.name); // TS knows data is User here
    } else {
      console.error("Invalid user data");
    }

    预期结果

    isUser 返回 true 时 TS 将 data 收窄为 User 类型;非法数据走 else 分支。

  5. 5

    添加泛型工具函数

    编写泛型工具函数(如 deepFreeze、groupBy)增强类型安全的复用能力。泛型让工具函数适用于多种类型而不丢失类型信息。

    代码
    function groupBy<T, K extends string | number>(
      items: T[],
      keyFn: (item: T) => K
    ): Record<K, T[]> {
      const result = {} as Record<K, T[]>;
      for (const item of items) {
        const key = keyFn(item);
        (result[key] ??= []).push(item);
      }
      return result;
    }
    
    // Usage
    const byAge = groupBy(users, u => u.age);

    预期结果

    groupBy 对任意类型数组按键分组,返回类型安全的 Record。

自己动手试试

你学到了什么

你 implemented builder 模式使用 TypeScript's 这个 返回类型 for fluent chaining. builder accumulates 部分状态 and 验证 completeness in 构建(). 这个模式是 used in 库如 Knex (SQL), Mongoose (MongoDB), and Axios (HTTP).

查阅不认识的术语

新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。

查看术语表

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误

← 返回主题