TypeScript interface, implements และ structural typing



implements

interface Serializable {
  serialize(): string;
}

interface Comparable<T> {
  compareTo(other: T): number;
}

class Version implements Serializable, Comparable<Version> {
  constructor(
    public major: number,
    public minor: number,
    public patch: number,
  ) {}

  serialize(): string {
    return `${this.major}.${this.minor}.${this.patch}`;
  }

  compareTo(other: Version): number {
    return (
      this.major - other.major ||
      this.minor - other.minor ||
      this.patch - other.patch
    );
  }
}

implements = “TS ตรวจว่า class นี้มี member ครบตาม interface” — ถ้าขาด serialize() → error

implements ไม่ได้เปลี่ยนพฤติกรรม class — แค่ check เท่านั้น (ต่างจาก extends ที่รับ code มาจริง)

implements ไม่ทำให้ field type เข้ม

interface Named {
  name: string;
}

class Person implements Named {
  name;   // Error: implicitly has 'any' — implements ไม่ทำให้ name เป็น string อัตโนมัติ
}

class Person2 implements Named {
  name: string = "";   // ต้องประกาศ type เอง
}

implements ไม่ “ยกร่าง” type ให้ — ต้องเขียน type ของ field เอง

structural typing (duck typing) — หัวใจของ TS

TS สนแค่ “shape” ไม่สนว่ามาจาก class/interface ไหน — “ถ้ามันเดินเหมือนเป็ด ร้องเหมือนเป็ด มันคือเป็ด”

interface Point {
  x: number;
  y: number;
}

function printPoint(p: Point) {
  console.log(`(${p.x}, ${p.y})`);
}

// ทั้งหมดนี้ใช้ได้ — ไม่มีคำว่า "implements Point" ที่ไหนเลย
printPoint({ x: 1, y: 2 });                          // object literal
printPoint(new Vector(3, 4));                         // class ที่บังเอิญมี x, y
printPoint({ x: 1, y: 2, z: 3 });                    // มี extra ก็ได้ (ผ่านตัวแปร)

class NamedPoint {
  constructor(public x: number, public y: number, public label: string) {}
}
printPoint(new NamedPoint(5, 6, "A"));   // OK — มี x, y ครบ

structural เทียบ nominal

structural (TS, Go)nominal (Java, C#)
เกณฑ์shape ตรงกันประกาศ implements/extends ชัด ๆ
class ที่บังเอิญ shape เหมือนใช้แทนกันได้ใช้แทนกันไม่ได้
object literalใช้แทน class ได้ไม่ได้ (ต้อง new)
class Dog {
  bark() {}
}
class Robot {
  bark() {}
}

function makeItBark(thing: Dog) {
  thing.bark();
}

makeItBark(new Robot());   // ✅ OK ใน TS! Robot มี bark() → shape ตรง
                            // ❌ Java จะ error

ผลที่ตามมาของ structural typing

ข้อดี: ยืดหยุ่นมาก — เขียน function ที่รับ “อะไรก็ได้ที่มี method นี้” ได้ง่าย, mock ตอนเทสต์ง่าย (แค่ object ที่มี shape ตรง)

ข้อควรระวัง: class ที่บังเอิญ shape เหมือนกันจะสับสนได้

type Meters = { value: number };
type Feet = { value: number };

function walk(distance: Meters) {}
walk({ value: 100 } as Feet);   // ✅ TS ยอม — shape เหมือน (bug ที่ type ไม่ช่วยจับ)

แก้ด้วย branded type (nominal จำลอง):

type Meters = number & { readonly __brand: "meters" };
type Feet = number & { readonly __brand: "feet" };

function meters(n: number): Meters {
  return n as Meters;
}

function walk(distance: Meters) {}
walk(meters(100));       // OK
walk(100);               // Error: number ไม่ใช่ Meters
walk(5 as Feet);         // Error: Feet ไม่ใช่ Meters

class เป็นทั้ง value และ type

class User {
  constructor(public name: string) {}
}

const u: User = new User("อร");   // User (type)
const C = User;                    // User (value — class constructor)
const u2 = new C("บอย");

// InstanceType<typeof User> === User

private field ทำให้ class เป็น nominal บางส่วน

class Secret {
  private key = "abc";
}
class NotSecret {
  private key = "abc";
}

let s: Secret = new NotSecret();
// Error: Type 'NotSecret' is not assignable to type 'Secret'.
//        Types have separate declarations of a private property 'key'.

class ที่มี private/protected member เทียบกันแบบ nominal (ต้องมาจาก declaration เดียวกัน) — เป็นวิธีทำ nominal ใน TS

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

  • คิดว่า implements ยกร่าง type ให้ field — ต้องเขียน name: string เอง
  • คิดว่าต้อง implements ถึงจะส่ง object เข้า function ที่รับ interface ได้ — structural typing: shape ตรงก็พอ
  • class ที่ shape บังเอิญเหมือนกันปนกัน — ใช้ branded type / private member เมื่อต้อง nominal
  • implements แล้วคิดว่าได้ code จาก interface — ไม่มี code ใน interface; แค่ check
  • as Feet เพื่อ “แปลง” — assertion ไม่ตรวจ runtime, structural typing ยอมให้ shape เดียวกันปนกัน

สรุป

  • class C implements I — TS ตรวจว่า C มี member ครบตาม I (ไม่ยกร่าง type ให้ field, ไม่ให้ code)
  • structural typing — TS สนแค่ shape ไม่สนว่ามาจากไหน; object literal / class อื่นที่ shape ตรงใช้แทนกันได้
  • ต่างจาก nominal typing (Java) — class ที่บังเอิญเหมือนกันปนกันได้
  • ทำ nominal ด้วย branded type (number & { __brand: "meters" }) หรือ private member
  • class เป็นทั้ง value (constructor) และ type (instance shape)

บทถัดไปว่าด้วย getter/setter, static, #private fields (JS runtime private) และ readonly