Utility types เป็น generic types ที่สร้างมาแล้วซึ่งแปลงประเภทที่มีอยู่ ดังนั้นคุณจึงสามารถหากำเนิดประเภทใหม่แทนที่จะกำหนดซ้ำ พวกมันทำให้ประเภท DRY และสอดคล้องกับแหล่งข้อมูลของพวกมัน
ts
{ : ; : ; : ; : ; }
<>;
<>;
<>;
<, | >;
<, >;
Utility types เป็น generic types ที่สร้างมาแล้วซึ่งแปลงประเภทที่มีอยู่ ดังนั้นคุณจึงสามารถหากำเนิดประเภทใหม่แทนที่จะกำหนดซ้ำ พวกมันทำให้ประเภท DRY และสอดคล้องกับแหล่งข้อมูลของพวกมัน
{ : ; : ; : ; : ; }
<>;
<>;
<>;
<, | >;
<, >;
// Update endpoint: accept any subset of fields
function update(id: number, changes: Partial<User>) { ... }
update(1, { name: "New" }); // ✅ only the fields you change
// Create endpoint: everything except the server-generated id
type CreateUser = Omit<User, "id">;
หากคุณเพิ่มฟิลด์ให้กับ User ทั้งหมดนี้จะอัปเดตโดยอัตโนมัติ — ไม่มีคำจำกัดความที่สองที่ต้องลืม
Record<string, number>; // { [key: string]: number } — dictionaries
ReturnType<typeof fn>; // the return type of a function
Parameters<typeof fn>; // tuple of a function's parameter types
NonNullable<string | null>; // string (strips null/undefined)
Extract<T, U>; Exclude<T, U>; // filter members of a union
Utility types ให้คุณสามารถแสดงความสัมพันธ์ระหว่างประเภท ("แบบฟอร์มสร้าง คือ user ลบ id") โดยใช้วิธีการประกาศ
พวกมันลดความซ้ำซ้อน รักษาประเภทที่หากำเนิดให้สอดคล้องโดยอัตโนมัติกับแหล่งข้อมูล และปรากฏอยู่ทั่วทั้ง codebases ในโลกจริง — โดยเฉพาะอย่างยิ่ง Partial สำหรับการอัปเดต Omit/Pick สำหรับ DTOs และ Record สำหรับแผนที่