Overview
ใน JavaScript ทุกอย่างแทบจะเป็น Object แต่ใน TypeScript เราต้องมี "พิมพ์เขียว" (Blueprints) เพื่อบอกรูปร่างหน้าตาของ Object นั้นๆ ซึ่งก็คือ Interface และ Type Alias การเลือกใช้ให้ถูกจะช่วยให้โค้ดขยายต่อได้ง่าย (Extensible)
Key Ideas
1. Interface vs Type Alias
คำถามโลกแตก: ใช้อะไรดี?
- Interface: เหมาะกับ Object ที่เป็นตัวแทนของ Business Logic (เช่น
User,Product) และสามารถสืบทอด (Extends) ได้ดี - Type Alias: เหมาะกับ Union Types, Tuple หรือ Function types ที่ซับซ้อน
✅ Best Practice: เริ่มต้นด้วย Interface เสมอ ถ้าทำไม่ได้ค่อยใช้ Type
2. Properties Modifiers
- Optional (
?): มีก็ได้ ไม่มีก็ได้ - Readonly: ห้ามแก้ไขหลังจากสร้างเสร็จ
3. Destructuring & Spreading
- Destructuring: ดึงค่าออกมาใส่ตัวแปร
- Spread (
...): Copy หรือ Merge Object
Example
// 1. Interface with Modifiers
interface UserConfig {
readonly id: string; // แก้ไม่ได้
username: string;
theme?: "light" | "dark"; // มีก็ได้ ไม่มีก็ได้
}
function initUser(config: UserConfig) {
// config.id = "new"; // ❌ Error: Read-only
console.log(`User: ${config.username}, Theme: ${config.theme || "default"}`);
}
// 2. Extends (การสืบทอด)
interface AdminConfig extends UserConfig {
permissions: string[];
}
const admin: AdminConfig = {
id: "admin-1",
username: "SuperAdmin",
permissions: ["delete-users"],
};
Pitfalls (สิ่งที่ควรระวัง)
❌ 1. ใช้ any กับ Object
// ❌ ปลอดภัยต่ำ
const user: any = { name: "John" };
user.age = 30; // ทำได้ แต่ไม่มีใครรู้ว่ามี property นี้
// ✅ ใช้ Interface
interface User {
name: string;
age?: number;
}
const user: User = { name: "John" };
❌ 2. Excess Property Checks
TypeScript จะด่าถ้าเราส่ง Object Literal ที่มี "ของแถม" (Key ที่ไม่ได้นิยาม) เข้าไปในฟังก์ชัน
interface Point {
x: number;
y: number;
}
function draw(p: Point) {}
// Error: Object literal may only specify known properties
draw({ x: 10, y: 20, z: 30 });