TypeScript getter/setter, static และ private field



getter / setter

class Temperature {
  private _celsius: number;

  constructor(celsius: number) {
    this._celsius = celsius;
  }

  get celsius(): number {
    return this._celsius;
  }

  set celsius(value: number) {
    if (value < -273.15) {
      throw new Error("ต่ำกว่าศูนย์สัมบูรณ์");
    }
    this._celsius = value;
  }

  get fahrenheit(): number {
    return this._celsius * 9 / 5 + 32;    // computed — ไม่มี setter = read-only
  }

  set fahrenheit(value: number) {
    this._celsius = (value - 32) * 5 / 9;
  }
}

const t = new Temperature(25);
console.log(t.celsius);       // 25 — เรียกเหมือน property (ไม่มีวงเล็บ)
console.log(t.fahrenheit);    // 77
t.celsius = 30;              // เรียก setter
t.fahrenheit = 100;         // เรียก setter — _celsius กลายเป็น 37.7...
t.celsius = -300;           // throw

getter/setter เข้าถึงเหมือน property (t.celsius ไม่ใช่ t.celsius()) — ใช้เมื่อต้อง validate, compute, หรือ log การเข้าถึง

getter อย่างเดียว (ไม่มี setter) = read-only property

static members

class MathUtils {
  static readonly PI = 3.14159265358979;

  static square(n: number): number {
    return n * n;
  }

  static #instanceCount = 0;

  constructor() {
    MathUtils.#instanceCount++;
  }

  static getInstanceCount(): number {
    return MathUtils.#instanceCount;
  }
}

MathUtils.PI;              // เข้าถึงผ่าน class ไม่ใช่ instance
MathUtils.square(5);      // 25

static = ของ class เอง ไม่ใช่ของแต่ละ instance — factory method, ค่าคงที่, counter

class User {
  private constructor(public id: string, public name: string) {}

  // factory method — validate + สร้าง
  static create(name: string): User {
    if (!name.trim()) throw new Error("ต้องมีชื่อ");
    return new User(crypto.randomUUID(), name);
  }

  static fromJSON(json: string): User {
    const data = JSON.parse(json) as { id: string; name: string };
    return new User(data.id, data.name);
  }
}

const u = User.create("อร");    // ผ่าน factory
// new User(...)                 // Error: constructor is private

#private fields — private จริงตอน runtime

TypeScript มี 2 แบบ private:

class Widget {
  private tsPrivate = 1;       // TS private — compile-time เท่านั้น
  #jsPrivate = 2;              // JS private (# syntax) — runtime จริง

  reveal() {
    console.log(this.tsPrivate, this.#jsPrivate);
  }
}

const w = new Widget();
w.tsPrivate;          // Error ตอน compile — แต่ w["tsPrivate"] ยังเข้าถึงได้ตอน runtime
w.#jsPrivate;         // Error ทั้ง compile และ runtime (SyntaxError จริง ๆ)
(w as any).tsPrivate; // 1 — bypass ได้
(w as any).#jsPrivate; // ไม่ได้ — # เป็น private จริง
private (TS)#field (JS)
ตรวจcompile-timecompile + runtime
bypass ด้วย as any / obj["x"]ได้ไม่ได้
เห็นใน JSON.stringify / Object.keysได้ไม่ได้
nominal typingใช่ (บทที่ 19)ใช่

ใช้ #field เมื่อต้องการ encapsulation จริง ๆ (library, security-sensitive); private พอสำหรับงานทั่วไป (สั้นกว่า, ทำงานกับ decorator/reflection บางตัวได้)

static block (TS 4.4+)

class Config {
  static settings: Record<string, string>;
  static #initialized = false;

  static {
    // รันครั้งเดียวตอน class ถูกโหลด — สำหรับ init ที่ซับซ้อน
    Config.settings = loadFromEnv();
    Config.#initialized = true;
    console.log("Config พร้อมใช้งาน");
  }
}

readonly + static

class HttpStatus {
  static readonly OK = 200;
  static readonly NOT_FOUND = 404;
  static readonly SERVER_ERROR = 500;
}

HttpStatus.OK;              // 200
HttpStatus.OK = 201;       // Error: read-only

(union ของ literal มักดีกว่าสำหรับ enum-like — บทที่ 8)

accessor keyword (TS 5.0) + decorator

class Model {
  accessor name = "";   // สร้าง getter/setter อัตโนมัติ + รองรับ decorator
}

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

  • เรียก getter ด้วยวงเล็บ — t.celsius() ผิด; getter เข้าถึงเหมือน property (t.celsius)
  • getter ที่มี side effect / คำนวณหนัก — ผู้ใช้คาดว่า property access เร็ว; ทำเป็น method ถ้าหนัก
  • สับสน private (TS) กับ #field (JS) — # เป็น runtime private จริง, private เป็น compile-time
  • #field แล้ว JSON.stringify ไม่เห็น — ต้อง toJSON() เอง
  • static field ที่ต้องการค่าจาก instance — static ไม่มี this ที่เป็น instance
  • static { } block คิดว่ารันทุก instance — รันครั้งเดียวตอน class โหลด
  • this ใน static method — this = class constructor ไม่ใช่ instance

สรุป

  • getter/setter (get x() / set x(v)) — เข้าถึงเหมือน property; validate/compute/read-only
  • static member — ของ class ไม่ใช่ instance; factory method (User.create()), ค่าคงที่, counter
  • #field (JS private) — private จริงตอน runtime, bypass ไม่ได้, ไม่เห็นใน JSON.stringify
  • private (TS) — compile-time เท่านั้น, bypass ได้ด้วย as any — พอสำหรับงานทั่วไป
  • static { } block — init ครั้งเดียวตอน class โหลด
  • static readonly X = ... — ค่าคงที่ (union ของ literal มักดีกว่า)

บทถัดไปว่าด้วย decorators — TC39 decorators ใน TS 5.0, class/method decorator และ use case