Dark mode
Declared Types ( type ที่ประกาศ)
Interface (อินเทอร์เฟซ)
Interface ใช้สำหรับกำหนดโครงสร้างของ object โดยระบุ type ของ properties และ methods
ts
interface User {
id: number;
name: string;
email?: string; // Optional property
greet(): string; // Method
}
const user: User = {
id: 1,
name: "John",
greet: () => `Hello, I'm John`,
};
Type Aliases (type )
Type Aliases ใช้สร้างชื่อใหม่ให้กับ type ที่มีอยู่ หรือรวมหลาย type เข้าด้วยกัน
ts
type ID = number | string;
type UserRole = "admin" | "user" | "guest";
type UserProfile = {
id: ID;
role: UserRole;
};
Declared Types (d.ts)
ไฟล์ .d.ts ใช้สำหรับประกาศ type (type declarations) โดยเฉพาะ
ts
// types/user.d.ts
declare interface User {
id: number;
name: string;
}
declare type UserList = User[];
หมายเหตุ:
- ไฟล์ .d.ts ไม่มีโค้ดการทำงานจริง (runtime code)
- ใช้กับไลบรารี JavaScript ที่ไม่มี type definitions
- ช่วยให้ IDE แสดงคำแนะนำได้ถูกต้อง