ข้ามไปเนื้อหาหลัก

TypeScript Utility Types ที่ใช้บ่อยสุด

Built-in utility types ที่ TypeScript มีให้ใช้ได้เลยโดยไม่ต้อง import

type User = {
  id: number;
  name: string;
  email: string;
  role: 'admin' | 'user';
};

// Partial — ทำทุก field เป็น optional (ดีสำหรับ PATCH request)
type UserUpdate = Partial<User>;

// Required — ทำทุก field เป็น required (ตรงข้าม Partial)
type StrictUser = Required<User>;

// Pick — เลือกเฉพาะ field ที่ต้องการ
type UserPreview = Pick<User, 'id' | 'name'>;

// Omit — ตัด field ออก
type PublicUser = Omit<User, 'email'>;

// Readonly — ห้ามแก้ค่าหลัง assign
type FrozenUser = Readonly<User>;

// Record — map ของ key → value type
type RolePermissions = Record<User['role'], string[]>;
// = { admin: string[]; user: string[] }

ที่ใช้บ่อยในงานจริง:

// ReturnType — ดึง return type จาก function
type ApiResponse = ReturnType<typeof fetchUser>;

// Parameters — ดึง parameter types
type FetchArgs = Parameters<typeof fetch>;

// NonNullable — ตัด null | undefined ออก
type DefiniteUser = NonNullable<User | null | undefined>;

Utility types เหล่านี้ implement ด้วย Mapped Types + Conditional Types ใน TypeScript เอง