Skip to content

类型-Safe API 客户端

中等 约 25 分钟

你将构建什么

获取 wrapper 那个 takes URL and expected 响应类型 T, 然后返回 Promise<T>. TypeScript 验证那个 callers use 正确响应 shape.

学习目标

  • Use generics 到类型 API 响应 shapes
  • Apply 类型 assertions safely 之后运行时检查
  • Handle 错误使用输入 result 对象
  • 理解边界之间编译-时间 and 运行时类型

前置要求

  • Generics 基础
  • 接口
  • 异步/等待
  • 获取 API

步骤

  1. 1

    定义响应类型

    创建接口 for API 响应你 expect. 这些类型是 编译-时间仅 — 它们描述 shape 的数据.

    代码
    interface User { id: number; name: string; email: string; }
    interface Post { id: number; title: string; body: string; }

    预期结果

    Two 接口是 定义. 否运行时 code yet.

  2. 2

    编写 generic 获取函数

    创建函数 apiFetch<T> 那个 calls 获取, parses JSON, and asserts result as T. generic 参数 lets callers specify expected 类型.

    代码
    async function apiFetch<T>(url: string): Promise<T> {
      const res = await fetch(url);
      if (!res.ok) throw new Error(`HTTP ${res.status}`);
      return (await res.json()) as T;
    }

    预期结果

    generic 函数那个返回 Promise<T> for 任何 URL.

  3. 3

    Use 输入客户端

    Call apiFetch 使用 explicit 类型参数. TypeScript 现在 knows shape 的每个响应, 启用 autocomplete and 类型检查.

    代码
    const user = await apiFetch<User>("/api/users/1");
    console.log(user.name); // type-safe access
    
    const post = await apiFetch<Post>("/api/posts/1");
    console.log(post.title); // type-safe access

    预期结果

    Autocomplete 工作 for 用户.name and post.title. Typos 是 caught at 编译时间.

  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。

自己动手试试

你学到了什么

你构建 generic API 客户端哪里返回类型是 determined 通过 caller. 这个是 大多数常见真实-世界 use 的 generics — bridging untyped 运行时数据到 输入编译-时间接口.

查阅不认识的术语

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

查看术语表

解读错误信息

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

查看错误

← 返回主题