Skip to content

Interfaces และ Type Aliases

Interfaces คือเครื่องมือหลักของ TypeScript ในการกำหนด โครงสร้างของ object ทำให้โค้ดมี contract ชัดเจน

interface User {
id: number;
name: string;
email: string;
age: number;
}
const user: User = {
id: 1,
name: "สมชาย",
email: "somchai@example.com",
age: 28
};
// 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;
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! readonly
// Base interface
interface BaseEntity {
id: number;
createdAt: Date;
updatedAt: Date;
}
// Extend — สืบทอด properties ทั้งหมดจาก parent
interface Student extends BaseEntity {
name: string;
studentId: string;
gpa: number;
}
// Multiple extend
interface 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"]
};
// Interface สำหรับ function signature
interface SearchFunction {
(query: string, limit: number): Promise<User[]>;
}
// Interface สำหรับ object ที่มี methods
interface UserService {
getUser(id: number): Promise<User>;
createUser(data: Omit<User, "id">): Promise<User>;
deleteUser(id: number): Promise<void>;
}
// เมื่อไม่รู้ชื่อ key ล่วงหน้า
interface Dictionary {
[key: string]: string;
}
const translations: Dictionary = {
hello: "สวัสดี",
goodbye: "ลาก่อน",
thanks: "ขอบคุณ"
};