Skip to content

类型-Safe 配置 Manager

简单 约 15 分钟

你将构建什么

ConfigManager 那个合并默认配置使用用户 overrides, 哪里 overrides 是部分<配置> and result 是 Readonly<配置>.

学习目标

  • Apply 部分, 必需, and Readonly utility 类型
  • 合并 configs 使用类型 safety
  • Prevent mutation 的最终配置
  • 理解 utility 类型 composition

前置要求

  • Utility 类型
  • 接口
  • 对象 spread

步骤

  1. 1

    定义配置接口

    创建配置接口使用必需字段. 这个是 完整 shape 的配置.

    代码
    interface Config {
      port: number;
      host: string;
      debug: boolean;
      maxConnections: number;
    }

    预期结果

    配置接口使用 four 必需字段.

  2. 2

    构建配置 manager

    创建函数那个 takes defaults (配置) and overrides (部分<配置>), 合并它们, and 返回 Readonly<配置> 到 prevent mutation.

    代码
    function createConfig(
      defaults: Config,
      overrides: Partial<Config>
    ): Readonly<Config> {
      return Object.freeze({ ...defaults, ...overrides });
    }

    预期结果

    函数那个合并 configs and 返回 frozen, readonly result.

  3. 3

    Use 配置 manager

    创建配置使用 defaults and 部分 overrides. result 是输入 and 不可变.

    代码
    const config = createConfig(
      { port: 3000, host: "localhost", debug: false, maxConnections: 10 },
      { port: 8080, debug: true }
    );
    console.log(config.port); // 8080
    // config.port = 4000; // Compile error: readonly

    预期结果

    配置是 合并正确地 and cannot 是 mutated at 编译时间 or 运行时.

  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。

自己动手试试

你学到了什么

你 composed utility 类型到 创建 flexible, safe 配置系统. 部分允许部分 overrides, Readonly prevents mutation, and spread 合并是 类型-检查. 这个是 如何真实-世界配置库 如 dotenv and convict 工作.

查阅不认识的术语

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

查看术语表

解读错误信息

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

查看错误

← 返回主题