สำหรับมือใหม่ที่เริ่มเขียน TypeScript มาสักพักนึงอยากให้ลองศึกษา Utility Types ของ TypeScript เพิ่มเติมกันด้วยนะครับ :)
.
1. Partial<Type>
ทำให้ทุก property ทั้งหมดใน type เป็น optional
ตัวอย่าง:
interface Customer {
id: string
name: string
}
type PartialCustomer = Partial<Customer>
// ผลลัพธ์: { id?: string; name?: string }
อาจใช้ในกรณี request ตอนอัปเดตข้อมูลก็ได้ เช่น UpdateCustomerRequest เป็นต้น
.
2. Record<Keys, Type>
ช่วยสร้างชนิดข้อมูล object ที่ key ของ property เป็น Keys และ value ของ property เป็น Type ได้
ตัวอย่าง:
type Staff = “John” | “Bob”
const canPlayFootball: Record<Staff, boolean> = {
John: true,
Bob: false,
}
และยังใช้ร่วมกับ Partial<Record<…>> เมื่อไม่ต้องการ map ทุก key แต่ยังอยากได้ type safety
.
3. Omit<Type, Keys>
ลบ property บางตัว ออกจาก type ที่ต้องการ
ตัวอย่าง:
interface Product {
name: string
price: number
}
type ProductWithName = Omit<Product, “price”>
// ผลลัพธ์: { name: string }
.
4. ReturnType<Type>
ดึงชนิดข้อมูล (type) ของฟังก์ชันแบบ return ค่า
ตัวอย่าง:
function multiply(a: number, b: number): number {
return a * b
}
type Multiply(Return = ReturnType<typeof multiply>
// ผลลัพธ์: number
.
5. Readonly<Type>
ทำให้ property ทั้งหมดไม่สามารถถูกแก้ไขได้ (readonly)
ตัวอย่าง:
function resetScore(score: Readonly<Score>) {
score.count = 0 // จะ Error ตรงนี้
}
ใช้สำหรับให้รู้ว่าค่าจะต้องไม่ถูกเปลี่ยน ช่วยให้อ่านง่าย และป้องกันการแก้ไขโดยไม่ได้ตั้งใจ
.
สรุป การใช้ utility types จะช่วยให้โค้ดมีความยืดหยุ่น ปลอดภัย และลดความซับซ้อนได้ดีมาก
และโดยปกติ utility types จะทำงานแค่ระดับเดียว หากทุกคนต้องการรองรับแบบหลายระดับ (deep support) แนะนำ library ชื่อว่า ts-toolbelt https://github.com/millsp/ts-toolbelt นะครับ