Overview
การจัดการกลุ่มข้อมูล (Collection) เป็นสิ่งที่โปรแกรมเมอร์เจอตลอดเวลา TypeScript ช่วยให้การทำงานกับ Array ปลอดภัยขึ้นด้วยการบังคับชนิดข้อมูล และยังมี Tuple ที่ช่วยล็อคตำแหน่งของข้อมูลโครงสร้างที่แน่นอน
Key Ideas
1. Array Typing
การประกาศ Array ใน TypeScript ทำได้ 2 แบบหลัก
number[](นิยมใช้ที่สุด)Array<number>(Generic Style)
const scores: number[] = [10, 20, 30];
const names: Array<string> = ["Alice", "Bob"];
2. High Order Functions
หลีกเลี่ยงการใช้ for loop แบบดั้งเดิม แล้วหันมาใช้ Method ของ Array ที่อ่านง่ายกว่า
.map(): แปลงข้อมูล (ได้ Array ใหม่ขนาดเท่าเดิม).filter(): คัดกรองข้อมูล (ได้ Array ใหม่ที่เล็กลงหรือเท่าเดิม).reduce(): ยุบรวมข้อมูลเหลือค่าเดียว
3. Tuples (TS Only)
ใช้เมื่อเรารู้ จำนวน และ ชนิด ของข้อมูลในแต่ละตำแหน่งที่แน่นอน เหมาะสำหรับรับค่าพิกัด, ข้อมูล CSV, หรือ Return ค่าหลายตัวจากฟังก์ชัน
// ตำแหน่ง 0 ต้องเป็น string, ตำแหน่ง 1 ต้องเป็น number
let userProfile: [string, number] = ["John", 25];
Example: Modern Array Manipulation
interface Product {
name: string;
price: number;
inStock: boolean;
}
const products: Product[] = [
{ name: "Laptop", price: 30000, inStock: true },
{ name: "Mouse", price: 500, inStock: false },
{ name: "Keyboard", price: 1500, inStock: true },
];
// 1. Filter: เอาเฉพาะของที่มีขาย
const available = products.filter((p) => p.inStock);
// 2. Map: เอาแค่ชื่อสินค้า
const productNames = available.map((p) => p.name); // ["Laptop", "Keyboard"]
// 3. Reduce: ราคารวมของที่มีขาย
const totalPrice = available.reduce((sum, p) => sum + p.price, 0); // 31500
Pitfalls (สิ่งที่ควรระวัง)
❌ 1. ใช้ Tuple ผิดวัตถุประสงค์
Tuple เหมาะกับข้อมูลชุดเล็กๆ ที่ตำแหน่งมีความหมาย (เช่น [x, y]) อย่าใช้เก็บข้อมูลรายการยาวๆ ที่ควรจะเป็น Object
// ❌ อ่านยาก ไม่รู้ว่าตัวเลขคืออะไร
const user = ["John", 25, true, "Admin"];
// ✅ ใช้ Object/Interface ดีกว่า
const user = { name: "John", age: 25, ... };
❌ 2. ลืม Type Return ของ Reduce
reduce มักต้องการ Generic Type หรือ Initial Value เพื่อให้ TS รู้ว่าผลลัพธ์คืออะไร
// ✅ ระบุ Initial Value (0) เพื่อบอกว่าเป็น number
const total = nums.reduce((a, b) => a + b, 0);