Interfaces และ Type Aliases
Interfaces และ Type Aliases
Section titled “Interfaces และ Type Aliases”Interfaces คือเครื่องมือหลักของ TypeScript ในการกำหนด โครงสร้างของ object ทำให้โค้ดมี contract ชัดเจน
Interface พื้นฐาน
Section titled “Interface พื้นฐาน”interface User { id: number; name: string; email: string; age: number;}
const user: User = { id: 1, name: "สมชาย", email: "somchai@example.com", age: 28};// JS ไม่มี interface — ต้อง check ด้วย runtime validationconst user = { id: 1, name: "สมชาย", email: "somchai@example.com" };// ไม่มีการตรวจสอบโครงสร้าง ณ เวลา compilefrom dataclasses import dataclass
@dataclassclass User: id: int name: str email: str age: intCREATE TABLE users ( id SERIAL PRIMARY KEY, name VARCHAR(100) NOT NULL, email VARCHAR(255) NOT NULL, age INT NOT NULL);Interface vs Type Alias
Section titled “Interface vs Type Alias”// Interface — เหมาะกับ object shapes, สามารถ extend ได้interface Product { name: string; price: number;}
// Type Alias — ยืดหยุ่นกว่า ใช้กับ union, tuple ได้type ID = string | number;type Pair = [string, number];type Callback = (data: string) => void;Optional และ Readonly Properties
Section titled “Optional และ Readonly Properties”interface Profile { id: number; name: string; bio?: string; // optional — อาจมีหรือไม่มีก็ได้ avatar?: string; // optional readonly createdAt: Date; // readonly — แก้ไขไม่ได้หลัง assign}
const profile: Profile = { id: 1, name: "สมหญิง", createdAt: new Date() // bio และ avatar ไม่ใส่ก็ได้};
// profile.createdAt = new Date(); // Error! readonlyExtending Interfaces
Section titled “Extending Interfaces”// Base interfaceinterface BaseEntity { id: number; createdAt: Date; updatedAt: Date;}
// Extend — สืบทอด properties ทั้งหมดจาก parentinterface Student extends BaseEntity { name: string; studentId: string; gpa: number;}
// Multiple extendinterface TeachingAssistant extends Student { department: string; coursesAssisting: string[];}
const ta: TeachingAssistant = { id: 1, createdAt: new Date(), updatedAt: new Date(), name: "วิชัย", studentId: "STD-001", gpa: 3.8, department: "Computer Science", coursesAssisting: ["CS101", "CS201"]};Interfaces กับ Functions
Section titled “Interfaces กับ Functions”// Interface สำหรับ function signatureinterface SearchFunction { (query: string, limit: number): Promise<User[]>;}
// Interface สำหรับ object ที่มี methodsinterface UserService { getUser(id: number): Promise<User>; createUser(data: Omit<User, "id">): Promise<User>; deleteUser(id: number): Promise<void>;}Index Signatures
Section titled “Index Signatures”// เมื่อไม่รู้ชื่อ key ล่วงหน้าinterface Dictionary { [key: string]: string;}
const translations: Dictionary = { hello: "สวัสดี", goodbye: "ลาก่อน", thanks: "ขอบคุณ"};