Dark mode
Programming Paradigms in TypeScript
เรียนรู้รูปแบบการเขียนโปรแกรมต่างๆ ที่สามารถใช้กับ TypeScript
1. Object-Oriented Programming (OOP)
ts
// ตัวอย่างการใช้ Class และ Inheritance
class Animal {
constructor(public name: string) {}
makeSound(): void {
console.log("Some generic sound");
}
}
class Dog extends Animal {
constructor(name: string) {
super(name);
}
// Method Overriding
makeSound(): void {
console.log("Woof! Woof!");
}
}
const myDog = new Dog("Buddy");
myDog.makeSound(); // Output: Woof! Woof!
2. Functional Programming (FP)
ts
// ตัวอย่าง Higher-Order Functions
const numbers = [1, 2, 3, 4, 5];
// Pure function
const double = (x: number): number => x * 2;
// Function composition
const result = numbers
.map(double)
.filter(x => x > 5)
.reduce((acc, curr) => acc + curr, 0);
console.log(result); // Output: 18 (6 + 8 + 10)
3. Reactive Programming
ts
// ตัวอย่างการใช้ RxJS
import { fromEvent } from "rxjs";
import { debounceTime, filter, map } from "rxjs/operators";
// สร้าง observable จาก event
const searchInput = document.getElementById("search");
const search$ = fromEvent(searchInput, "input").pipe(
map((e: Event) => (e.target as HTMLInputElement).value),
filter(text => text.length > 2),
debounceTime(300),
);
// Subscribe เพื่อรับค่า
search$.subscribe(value => {
console.log("Searching for:", value);
});
ตารางเปรียบเทียบ
Paradigm | ข้อดี | ข้อเสีย |
---|---|---|
OOP | เข้าใจง่าย, ใกล้เคียงโลกความจริง | อาจมี state มากเกินไป |
FP | ลด side effects, เขียนเทสง่าย | เรียนรู้ยากสำหรับผู้เริ่มต้น |
Reactive | เหมาะกับงาน async, UI | เรียนรู้ยาก, ใช้กับบางกรณีเท่านั้น |
สรุป
TypeScript รองรับหลายรูปแบบการเขียนโปรแกรม เลือกใช้ให้เหมาะสมกับงาน
- ใช้ OOP สำหรับการจัดการ state ที่ซับซ้อน
- ใช้ FP สำหรับการประมวลผลข้อมูล
- ใช้ Reactive สำหรับการจัดการ asynchronous operations