ข้ามไปยังเนื้อหา

Classes & Advanced OOP

เกือบทุกอย่างในคอร์สนี้เป็น type — construct ที่อยู่ตอน compile time แล้วถูก erase ทิ้ง แต่ class ต่างออกไป เป็นหนึ่งในไม่กี่ declaration ที่สร้างทั้ง type และ value ชื่อ class เป็น type ที่คุณเอาไป annotate ได้ และในเวลาเดียวกันก็เป็น runtime constructor ที่เรียกด้วย new ได้

class User {
constructor(public name: string) {}
}
const u: User = new User("Ada"); // `User` เป็น TYPE (annotation) และ VALUE (constructor)

ธรรมชาติสองด้านนี้คือเหตุผลที่ class รู้สึกพิเศษ และเป็นเหตุผลที่ feature ของตัวเองแบ่งเป็นสองกลุ่ม: กลุ่มที่ compiler เช็คแล้ว erase (เช่น private) กับกลุ่มที่รอดไปถึง JavaScript ที่ emit ออกมา (เช่น #private field)

บทเรียนสิ่งที่คุณจะได้เรียนรู้
Classes, deepaccess modifier, readonly, parameter property, static, abstract, implements
this types & polymorphismpolymorphic this, this parameter และ pitfall เรื่อง binding ใน type system
Decoratorsdecorator แบบ stage-3 สมัยใหม่ — class, method, field และ factory
Mixins & compositionสร้าง behavior จาก class factory ที่ compose ได้ แทน hierarchy ลึก ๆ

TypeScript รองรับ extends inheritance แบบคลาสสิก แต่โมดูลนี้เน้นไปที่ feature ที่ community ใช้จริงใน code สมัยใหม่: composition over inheritance class hierarchy ที่ลึกมัก brittle ส่วน this type, decorator และ mixin ช่วยให้สร้าง behavior ที่ยืดหยุ่นและ reuse ได้โดยไม่ต้องพึ่ง inheritance

flowchart TB
  cls["class declaration"] --> typeworld["TYPE world
(erased): private, protected,
implements, abstract"]
  cls --> valueworld["VALUE world
(runtime): #private, static,
the constructor, methods"]
feature ของ class มีสองแบบ
อะไรทำให้ class พิเศษกว่า type alias หรือ interface?
feature ของ class อันไหนที่รอดไปถึง JavaScript ที่ emit ออกมา?
TypeScript OOP สมัยใหม่มักเลือกแนวทางออกแบบแบบไหน?