TypeScript decorators



decorator = ฟังก์ชันที่ “ห่อ” หรือ “แต่ง” class / method / field ด้วย syntax @name ก่อนการประกาศ

สองระบบ: TS 5.0+ รองรับ TC39 decorators (มาตรฐาน, Stage 3) — บทนี้เน้นตัวนี้ ระบบเก่า experimentalDecorators (tsconfig) ยังใช้ใน Angular/NestJS/TypeORM แต่ syntax และ signature ต่างกัน

เปิดใช้

TC39 decorators ไม่ต้องตั้ง flag ใน TS 5.0+ (แค่อย่าตั้ง "experimentalDecorators": true)

method decorator — logging

function logged<This, Args extends any[], Return>(
  target: (this: This, ...args: Args) => Return,
  context: ClassMethodDecoratorContext<This, typeof target>,
) {
  const methodName = String(context.name);

  return function (this: This, ...args: Args): Return {
    console.log(`เรียก ${methodName}(${args.join(", ")})`);
    const result = target.call(this, ...args);
    console.log(`${methodName} คืน ${result}`);
    return result;
  };
}

class Calculator {
  @logged
  add(a: number, b: number): number {
    return a + b;
  }
}

new Calculator().add(3, 4);
// เรียก add(3, 4)
// add คืน 7

decorator รับ (1) สิ่งที่ถูกแต่ง (method function) (2) context (ชื่อ, kind, …) — คืนตัวแทนใหม่ (หรือ undefined = ไม่เปลี่ยน)

class decorator

function sealed<T extends new (...args: any[]) => object>(
  target: T,
  context: ClassDecoratorContext,
) {
  console.log(`sealing class ${String(context.name)}`);
  Object.seal(target);
  Object.seal(target.prototype);
}

@sealed
class Config {
  host = "localhost";
}

class decorator รับ constructor + context — คืน constructor ใหม่ (แทนที่) หรือ undefined

field decorator — default / transform

function uppercase(
  target: undefined,
  context: ClassFieldDecoratorContext<unknown, string>,
) {
  return function (initialValue: string): string {
    return initialValue.toUpperCase();
  };
}

class User {
  @uppercase
  role = "admin";
}

new User().role;   // "ADMIN"

decorator ที่รับ argument — decorator factory

function minLength(min: number) {
  return function (
    target: undefined,
    context: ClassFieldDecoratorContext<unknown, string>,
  ) {
    return function (initialValue: string): string {
      if (initialValue.length < min) {
        throw new Error(`${String(context.name)} ต้องยาวอย่างน้อย ${min}`);
      }
      return initialValue;
    };
  };
}

class Form {
  @minLength(8)
  password = "1234";   // throw: password ต้องยาวอย่างน้อย 8
}

@minLength(8) — เรียก factory ด้วย 8 → คืน decorator จริง

context.addInitializer — hook

function bound<This, Args extends any[], Return>(
  target: (this: This, ...args: Args) => Return,
  context: ClassMethodDecoratorContext<This>,
) {
  const methodName = context.name;
  context.addInitializer(function (this: This) {
    // รันตอนสร้าง instance — ผูก this ให้ method
    (this as any)[methodName] = (target as any).bind(this);
  });
}

class Counter {
  count = 0;

  @bound
  increment() {
    this.count++;
  }
}

const c = new Counter();
const inc = c.increment;
inc();   // OK — this ถูกผูกไว้ (แทน arrow field)

use case ที่พบบ่อย

  • logging / tracing — log ทุกการเรียก method
  • memoization / caching — cache ผลของ method
  • validation — validate argument / field value
  • timing — วัดเวลา method
  • access control — เช็คสิทธิ์ก่อนรัน method
  • dependency injection — Angular/NestJS @Injectable, @Controller
  • ORM mapping — TypeORM @Entity, @Column

experimentalDecorators แบบเก่า (สำหรับ legacy)

// tsconfig.json — สำหรับ Angular/NestJS/TypeORM ปัจจุบัน
{
  "compilerOptions": {
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true
  }
}

signature เก่า: (target, propertyKey, descriptor) — คนละแบบกับ TC39 อย่าปนกัน framework จะบอกว่าต้องใช้แบบไหน

เมื่อไรไม่ใช้ decorator

  • โค้ดทั่วไปที่ higher-order function / composition ทำได้ชัดกว่า
  • decorator ทำให้ตามยากว่า method จริงทำอะไร (magic)
  • ไม่ได้ใช้ framework ที่ต้องการ decorator

decorator เหมาะกับ cross-cutting concern (logging, caching, auth) ที่ต้องแนบกับหลาย method โดยไม่อยากซ้ำโค้ด

เรื่องที่คนมักพลาด

  • ปน TC39 กับ experimental decorators — signature ต่างกันสิ้นเชิง; framework บอกว่าใช้แบบไหน
  • ตั้ง experimentalDecorators: true แล้วใช้ syntax TC39 — ได้ระบบเก่า
  • decorator ไม่ return เมื่อต้องแทนที่ — return undefined = ไม่เปลี่ยน; ต้อง return function ใหม่
  • field decorator return ค่าไม่ใช่ function — field decorator return (initialValue) => newValue
  • ใช้ decorator กับทุกอย่าง — magic เยอะ, debug ยาก; ใช้กับ cross-cutting concern
  • context.name เป็น string | symbol — String(context.name) ก่อนใช้

สรุป

  • decorator @name — ฟังก์ชันที่แต่ง class/method/field
  • TC39 decorators (TS 5.0+, ไม่ต้องตั้ง flag): (target, context) => replacement
  • decorator factory @minLength(8) — ฟังก์ชันที่ return decorator (รับ argument)
  • context.addInitializer(fn) — hook รันตอนสร้าง instance
  • use case: logging, caching, validation, timing, DI, ORM — cross-cutting concern
  • experimental decorators (tsconfig flag) — ระบบเก่า, signature ต่าง, ยังใช้ใน Angular/NestJS/TypeORM

จบเฟส class บทถัดไปเข้าเฟสเขียนโค้ดจริง เริ่มที่ modules — import/export, import type และ path alias