Dark mode
Object Types (ประเภทอ็อบเจกต์)
Interface
ใช้กำหนดโครงสร้างของอ็อบเจกต์
ts
interface Product {
id: number;
name: string;
price: number;
inStock?: boolean; // Optional property
readonly createdAt: Date; // ไม่สามารถแก้ไขค่าได้
}
const laptop: Product = {
id: 1,
name: "MacBook Pro",
price: 45000,
createdAt: new Date(),
};
// laptop.createdAt = new Date(); // Error เพราะเป็น readonly
Type Aliases
ทางเลือกแทน interface สำหรับกำหนดประเภท
ts
type Point = {
x: number;
y: number;
};
const center: Point = {
x: 0,
y: 0,
};