TypeScript การสืบทอดและ abstract class
extends
class Animal {
constructor(public name: string) {}
move(distance: number): void {
console.log(`${this.name} เคลื่อนที่ ${distance} เมตร`);
}
}
class Dog extends Animal {
constructor(name: string, public breed: string) {
super(name); // ต้องเรียก super() ก่อนใช้ this
// this.name ใช้ได้หลัง super()
}
bark(): void {
console.log(`${this.name} เห่า!`);
}
}
const d = new Dog("โฮ่ง", "โกลเด้น");
d.move(10); // จาก Animal
d.bark(); // จาก Dog
d.name; // จาก Animal
d.breed; // จาก Dogต้อง super(...) ก่อน this ใน constructor ของ subclass — ไม่งั้น error
override method
class Dog extends Animal {
constructor(name: string) {
super(name);
}
move(distance: number): void {
console.log(`${this.name} วิ่ง ${distance} เมตร`); // override
}
}
const d = new Dog("บ๊อบ");
d.move(20); // "บ๊อบ วิ่ง 20 เมตร"เรียก method ของแม่ด้วย super.method():
class Dog extends Animal {
move(distance: number): void {
console.log("(หาง กระดิก)");
super.move(distance); // เรียกของ Animal ต่อ
}
}override keyword + noImplicitOverride
class Dog extends Animal {
override move(distance: number): void { // ระบุว่าตั้งใจ override
super.move(distance);
}
override mvoe(): void {} // Error: This member cannot have an 'override' modifier
// because it is not declared in the base class 'Animal'
}ตั้ง "noImplicitOverride": true — บังคับให้ทุก override ต้องมีคำว่า override จับ typo ชื่อ method (mvoe แทน move จะสร้าง method ใหม่ ไม่ override) และจับกรณีแม่ลบ method แล้วลูกยังมี
protected — subclass เข้าถึงได้
class Animal {
protected energy = 100;
constructor(public name: string) {}
protected consumeEnergy(amount: number): void {
this.energy -= amount;
}
}
class Dog extends Animal {
fetch(): void {
this.consumeEnergy(10); // OK — protected เข้าถึงจาก subclass ได้
console.log(`พลังงานเหลือ ${this.energy}`);
}
}
const d = new Dog("โฮ่ง");
d.energy; // Error: protectedabstract class
abstract class — ใช้เป็นฐานร่วมเท่านั้น สร้าง new ไม่ได้:
abstract class Shape {
abstract area(): number; // abstract method — ไม่มี body, ลูกต้อง implement
abstract readonly name: string; // abstract property
// concrete method — ใช้ area() ที่ลูกจะ implement
describe(): string {
return `${this.name} มีพื้นที่ ${this.area().toFixed(2)}`;
}
}
class Circle extends Shape {
readonly name = "วงกลม";
constructor(private radius: number) {
super();
}
area(): number {
return Math.PI * this.radius ** 2;
}
}
class Rectangle extends Shape {
readonly name = "สี่เหลี่ยม";
constructor(private width: number, private height: number) {
super();
}
area(): number {
return this.width * this.height;
}
}
const shapes: Shape[] = [new Circle(5), new Rectangle(3, 4)];
for (const s of shapes) {
console.log(s.describe());
}
new Shape(); // Error: Cannot create an instance of an abstract classถ้า Circle ลืม implement area() → error ตอนประกาศคลาส
abstract เทียบ interface
abstract class | interface | |
|---|---|---|
| มี implementation ได้ | ได้ (concrete method) | ไม่ได้ |
| มี field ได้ | ได้ | ได้ (แค่ shape) |
| ใช้ได้กี่ตัวต่อ 1 class | 1 (extends) | หลาย (implements) |
| runtime | มีอยู่ (class object) | หายตอน compile |
ใช้ abstract class เมื่ออยากแชร์ implementation; interface เมื่อแค่กำหนดสัญญา (มักผสม — บทที่ 19)
polymorphism
function totalArea(shapes: Shape[]): number {
return shapes.reduce((sum, shape) => sum + shape.area(), 0);
// ^ เรียก area() ของ subclass ที่แท้จริง (virtual dispatch)
}TS class มี virtual dispatch จริง — shape.area() เรียก implementation ของ subclass (ต่างจาก Go embedding — บทที่ 20 ของซีรีส์ Go)
discriminated union มักดีกว่า inheritance
สำหรับหลายกรณี discriminated union (บทที่ 7) เขียนง่ายกว่าและ exhaustiveness check ได้:
type Shape =
| { kind: "circle"; radius: number }
| { kind: "rectangle"; width: number; height: number };
function area(shape: Shape): number {
switch (shape.kind) {
case "circle": return Math.PI * shape.radius ** 2;
case "rectangle": return shape.width * shape.height;
}
}ใช้ class เมื่อมี state + behavior ผูกกัน และมี method หลายตัว; ใช้ union เมื่อเป็นแค่ “ข้อมูลหลายรูปแบบ”
เรื่องที่คนมักพลาด
- ใช้
thisก่อนsuper()ใน constructor ของ subclass — error - ลืม
super(...)เมื่อ subclass มี constructor — error - override โดยพิมพ์ชื่อผิด — สร้าง method ใหม่เงียบ ๆ; เปิด
noImplicitOverride+ ใช้override new AbstractClass()— error (ดี)- abstract property ที่ลูกไม่ implement — error ตอนประกาศคลาสลูก
- inheritance หลายชั้นลึก — ตามยากว่า method จริงมาจากไหน; composition/union มักดีกว่า
privateของแม่แล้วคิดว่าลูก override ได้ —privateลูกมองไม่เห็น; ใช้protected
สรุป
class B extends A— B ได้ field/method ของ A; constructor ต้องsuper(...)ก่อนthis- override ด้วยชื่อ method เดิม, เรียกของแม่ด้วย
super.method() overridekeyword +noImplicitOverride— จับ typo ชื่อ methodprotected— subclass เข้าถึงได้ (ต่างจากprivate)abstract class— สร้าง instance ไม่ได้;abstract method/propertyบังคับให้ลูก implement- class มี virtual dispatch จริง —
shape.area()เรียก implementation ของ subclass - discriminated union มักดีกว่าสำหรับ “ข้อมูลหลายรูปแบบ”
บทถัดไปว่าด้วย implements, class เป็น type และ structural (duck) typing