Dark mode
TypeScript with Object-Oriented Programming
เรียนรู้การเขียนโปรแกรมเชิงวัตถุด้วย TypeScript
1. Class และ Inheritance
ts
// ตัวอย่างการสร้างคลาส
class Person {
// Properties
private id: number;
protected name: string;
// Constructor
constructor(id: number, name: string) {
this.id = id;
this.name = name;
}
// Method
introduce(): string {
return `สวัสดีครับ/ค่ะ ผมชื่อ ${this.name}`;
}
}
// สร้าง instance
const person = new Person(1, "สมชาย");
console.log(person.introduce());
2. Access Modifiers
ts
class BankAccount {
// private - เข้าถึงได้เฉพาะภายในคลาส
private balance: number;
// public - เข้าถึงได้จากทุกที่ (ค่าเริ่มต้น)
public accountNumber: string;
// readonly - อ่านได้อย่างเดียว
public readonly createdAt: Date;
constructor(accountNumber: string) {
this.balance = 0;
this.accountNumber = accountNumber;
this.createdAt = new Date();
}
// Protected - เข้าถึงได้จากคลาสลูก
protected deduct(amount: number): void {
if (this.balance >= amount) {
this.balance -= amount;
}
}
}
3. Abstract Classes
ts
// Abstract class - ไม่สามารถสร้าง instance โดยตรงได้
abstract class Shape {
// Abstract method - ต้อง implement ในคลาสลูก
abstract calculateArea(): number;
// Regular method
displayArea(): void {
console.log(`พื้นที่: ${this.calculateArea()}`);
}
}
class Circle extends Shape {
constructor(private radius: number) {
super();
}
calculateArea(): number {
return Math.PI * this.radius ** 2;
}
}
const circle = new Circle(5);
circle.displayArea(); // แสดงพื้นที่วงกลม
4. Interfaces
ts
// กำหนดโครงสร้างของ object
interface ILogger {
log(message: string): void;
error(message: string): void;
}
// ใช้งาน interface
class ConsoleLogger implements ILogger {
log(message: string): void {
console.log(`[LOG] ${message}`);
}
error(message: string): void {
console.error(`[ERROR] ${message}`);
}
}
// ใช้ interface เป็น type
function processWithLogging(logger: ILogger, data: any): void {
try {
logger.log("Processing data...");
// ทำงานกับข้อมูล
logger.log("Process completed");
} catch (error) {
logger.error("An error occurred");
}
}
ตารางเปรียบเทียบ
Concept | คำอธิบาย | ตัวอย่างการใช้งาน |
---|---|---|
Encapsulation | การห่อหุ้มข้อมูล | ใช้ private/protected |
Inheritance | การสืบทอดคุณสมบัติ | extends |
Polymorphism | การมีหลายรูปแบบ | method overriding |
Abstraction | การซ่อนรายละเอียด | abstract class/interface |
สรุป
TypeScript มี features หลายอย่างที่ช่วยในการเขียน OOP:
- ใช้ class และ interfaces ในการออกแบบโครงสร้าง
- ใช้ access modifiers เพื่อควบคุมการเข้าถึง
- รองรับ abstract classes และ methods
- ใช้ decorators สำหรับเพิ่มฟีเจอร์พิเศษ