TypeScript class



TypeScript class = JavaScript class + type annotation + access modifier

class พื้นฐาน

class Rectangle {
  width: number;
  height: number;

  constructor(width: number, height: number) {
    this.width = width;
    this.height = height;
  }

  area(): number {
    return this.width * this.height;
  }
}

const rect = new Rectangle(3, 4);
console.log(rect.area());   // 12
  • ต้องประกาศ field (width: number) ก่อนใช้ — ต่างจาก JS ที่ implicit
  • strictPropertyInitialization (มากับ strict) บังคับให้ field ถูก init ใน constructor หรือมี default
class Foo {
  name: string;   // Error: Property 'name' has no initializer and is not definitely assigned
}

แก้: init ใน constructor, ให้ default, หรือ name?: string, หรือ name!: string (definite assignment — สัญญาว่าจะ set)

parameter properties — ย่อ

รูปแบบ “รับ argument แล้ว assign เข้า field” พบบ่อยมาก — TS ให้เขียนย่อ ใส่ modifier หน้าพารามิเตอร์ constructor:

class Rectangle {
  constructor(
    public width: number,
    public height: number,
  ) {}

  area(): number {
    return this.width * this.height;
  }
}

เทียบเท่าเวอร์ชันยาวข้างบน — TS สร้าง field + assign ให้เอง ใช้กับ public / private / protected / readonly

class UserService {
  constructor(
    private readonly db: Database,
    private readonly logger: Logger,
  ) {}

  async findUser(id: string) {
    this.logger.info("finding user", { id });
    return this.db.query("...", [id]);
  }
}

นี่คือ dependency injection แบบ TS — ส่ง dependency เข้า constructor, เก็บเป็น private field

access modifier

class BankAccount {
  public owner: string;         // เข้าถึงได้ทุกที่ (default — ไม่ต้องเขียน)
  private balance: number;       // เฉพาะในคลาสนี้
  protected accountType: string; // คลาสนี้ + คลาสลูก

  constructor(owner: string, initial: number) {
    this.owner = owner;
    this.balance = initial;
    this.accountType = "savings";
  }

  deposit(amount: number): void {
    if (amount <= 0) throw new Error("จำนวนเงินต้องมากกว่า 0");
    this.balance += amount;
  }

  getBalance(): number {
    return this.balance;
  }
}

const acc = new BankAccount("อร", 1000);
acc.owner;              // OK
acc.balance;            // Error: Property 'balance' is private
acc.deposit(500);       // OK — ผ่าน method ที่ตรวจเงื่อนไข

สำคัญ: private / protected ของ TS เป็น compile-time เท่านั้น — runtime ยังเข้าถึงได้ (acc["balance"]) ถ้าต้องการ private จริง ๆ ตอน runtime ใช้ #field (บทที่ 20)

readonly field

class Config {
  readonly host: string;
  readonly port: number;

  constructor(host: string, port: number) {
    this.host = host;    // set ใน constructor ได้
    this.port = port;
  }

  reset() {
    this.host = "localhost";   // Error: Cannot assign to 'host' because it is read-only
  }
}

method และ property เป็น field ที่เป็น function

class Counter {
  count = 0;

  // method ปกติ — this ผูกตอนเรียก
  increment() {
    this.count++;
  }

  // arrow function field — this ผูกกับ instance เสมอ (ใช้เป็น callback ได้)
  incrementBound = () => {
    this.count++;
  };
}

const c = new Counter();
const inc = c.increment;
inc();                    // TypeError: Cannot read properties of undefined (this หลุด)

const incB = c.incrementBound;
incB();                   // OK — this ผูกไว้แล้ว

arrow field มีประโยชน์กับ callback (event handler ใน React) แต่กินหน่วยความจำมากกว่า (1 function ต่อ instance)

class เป็น type

class Point {
  constructor(public x: number, public y: number) {}
}

function distance(a: Point, b: Point): number {
  return Math.hypot(a.x - b.x, a.y - b.y);
}

// object ที่มี shape เหมือน Point ก็ใช้ได้ (structural typing — บทที่ 19)
distance({ x: 0, y: 0 }, new Point(3, 4));   // 5

implements interface (เกริ่น — บทที่ 19)

interface Shape {
  area(): number;
}

class Circle implements Shape {
  constructor(private radius: number) {}
  area(): number {
    return Math.PI * this.radius ** 2;
  }
}

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

  • ไม่ init field — strictPropertyInitialization error; init ใน constructor หรือ default หรือ !
  • private แล้วคิดว่า runtime ป้องกัน — compile-time เท่านั้น; ใช้ #field สำหรับ runtime private
  • method เป็น callback แล้ว this หลุด — ใช้ arrow field หรือ .bind(this) หรือ () => obj.method()
  • ลืมว่า parameter property สร้าง field ให้ — constructor(public x: number) = มี this.x แล้ว
  • เข้าถึง field ก่อน super() ใน subclass — error (บทที่ 18)
  • this ใน static method — this = class เอง ไม่ใช่ instance
  • arrow field ทุก method “เพื่อความปลอดภัย” — เปลือง memory; ใช้เฉพาะ method ที่ส่งเป็น callback

สรุป

  • ต้องประกาศ field พร้อม type; strictPropertyInitialization บังคับ init (constructor / default / !)
  • parameter properties — constructor(public x: number, private db: Database) สร้าง field + assign ให้
  • access modifier: public (default), private (คลาสนี้), protected (คลาสนี้+ลูก) — compile-time เท่านั้น
  • readonly field — set ใน constructor ได้ แก้ทีหลังไม่ได้
  • method ปกติ (this ผูกตอนเรียก) vs arrow field (this ผูก instance — สำหรับ callback)
  • class ใช้เป็น type ได้ (structural — object shape เหมือนกันก็ผ่าน)

บทถัดไปว่าด้วยการสืบทอด — extends, super, abstract class และ override