May 9, 2026
TypeScript Utility Types
สรุป Utility Types ใน TypeScript ที่มีประโยชน์มากๆ ช่วยลดการเขียน Type ซ้ำซ้อนได้เยอะ
Partial<T>
เปลี่ยนให้ทุก Property ใน Type นั้นๆ สามารถ เป็นไปได้ที่จะไม่มีค่า (Optional)
ts
interface User {
id: number
name: string
email: string
}
// ทุก property จะกลายเป็น ? (optional) ทันที
// เทียบเท่า: { id?: number; name?: string; email?: string; }
type PartialUser = Partial<User>
const updateUser = (id: number, data: Partial<User>) => {
// data ไม่ต้องส่งมาครบทุกฟิลด์ก็ได้
}Required<T>
ตรงข้ามกับ Partial คือบังคับให้ทุก Property ต้องมีค่า (Required) แม้ว่าของเดิมมันจะเป็น Optional ก็ตาม
ts
interface Config {
theme?: string
language?: string
}
// เทียบเท่า: { theme: string; language: string; }
type RequiredConfig = Required<Config>Pick<T, Keys>
เลือกมาเฉพาะบาง Property ที่เราต้องการจาก Type ใหญ่ๆ
ts
interface Product {
id: number
name: string
description: string
price: number
stock: number
}
// เอามาแค่ name กับ price
// เทียบเท่า: { name: string; price: number; }
type ProductCard = Pick<Product, "name" | "price">Omit<T, Keys>
ตรงข้ามกับ Pick คือเลือกมาให้หมด ยกเว้น Property ที่เราไม่เอา (มักใช้เวลาจะส่งข้อมูลไปเซิร์ฟเวอร์แบบตัด ID ทิ้ง)
ts
interface UserRecord {
id: string
username: string
passwordHash: string
createdAt: Date
}
// เอาทุกอย่าง ยกเว้น passwordHash
type PublicUserProfile = Omit<UserRecord, "passwordHash">Record<Keys, Type>
เอาไว้สร้าง Object Type แบบง่ายๆ ที่ Key และ Value มีรูปแบบชัดเจน (มักใช้แทน {[key: string]: any})
ts
// สร้าง Type สำหรับดิกชันนารี หรือ Map
type RoleNames = Record<"admin" | "user" | "guest", string>
const roles: RoleNames = {
admin: "ผู้ดูแลระบบ",
user: "ผู้ใช้งานทั่วไป",
guest: "บุคคลทั่วไป",
}
// หรือใช้แบบ Dynamic
type TranslationMap = Record<string, string>ReturnType<Type>
ดึงเอา Return Type ของฟังก์ชันใดๆ ออกมาใช้งาน (สะดวกมากเวลาใช้ไลบรารีคนอื่นแล้วเขาไม่ได้ export type มาให้)
ts
function getUserData() {
return { id: 1, name: "Alice", role: "admin" }
}
// ดึง Type ที่ Return จากฟังก์ชัน getUserData
// เทียบเท่า: { id: number; name: string; role: string; }
type UserData = ReturnType<typeof getUserData>Awaited<Type>
เอาไว้แกะ Promise ออก เพื่อดูว่าค่าข้างในสุดๆ มันคือ Type อะไร (เหมาะกับการดึง Type จาก API)
ts
async function fetchScore(): Promise<number> {
return 100
}
// แกะ Promise ออก จะได้แค่ number
type ScoreType = Awaited<ReturnType<typeof fetchScore>>