Skip to content

Decorator Logger 系统

中等 约 25 分钟

你将构建什么

方法 decorator 那个 wraps 任何类 方法到 log 它的 name, 实参, and 返回值. 启用 experimentalDecorators in tsconfig.

学习目标

  • 理解 decorator 语法 and experimentalDecorators
  • 编写方法 decorator factory
  • Preserve 原始方法's 类型 signature
  • Apply cross-cutting concerns declaratively

前置要求

  • 类 in TypeScript
  • 函数
  • tsconfig 设置

步骤

  1. 1

    启用 decorator support

    添加 experimentalDecorators 到 tsconfig.JSON. Decorators 是 experimental feature 那个需要 explicit opt-in.

    代码
    {
      "compilerOptions": {
        "experimentalDecorators": true,
        "target": "ES2022"
      }
    }

    预期结果

    tsconfig.JSON 现在 supports decorator 语法.

  2. 2

    编写 log decorator

    创建方法 decorator 那个 replaces 原始方法使用 logging wrapper. wrapper calls 原始, logs result, and 返回它.

    代码
    function log(target: any, key: string, desc: PropertyDescriptor) {
      const original = desc.value;
      desc.value = function (...args: any[]) {
        console.log(`Calling ${key} with`, args);
        const result = original.apply(this, args);
        console.log(`${key} returned`, result);
        return result;
      };
    }

    预期结果

    decorator 函数那个 wraps 方法使用 logging.

  3. 3

    Apply decorator 到类

    Use @log decorator on 类方法. 每个 decorated 方法现在 automatically logs 它的 calls.

    代码
    class Calculator {
      @log
      add(a: number, b: number) { return a + b; }
      @log
      multiply(a: number, b: number) { return a * b; }
    }
    const calc = new Calculator();
    calc.add(2, 3); // logs: Calling add with [2, 3] / add returned 5

    预期结果

    方法 calls 是 automatically logged 不使用修改方法请求体.

  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。

自己动手试试

你学到了什么

你 used decorators 到添加 logging 不使用修改方法 bodies — cross-cutting concern applied declaratively. Decorators 是 powerful metaprogramming feature, 虽然它们需要 experimentalDecorators and 有 evolving 标准.

查阅不认识的术语

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

查看术语表

解读错误信息

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

查看错误

← 返回主题