Category: reference
TypeScript Utility Types ที่ใช้บ่อย
รวม Utility Types ใน TypeScript ที่ช่วยลดการเขียน type ซ้ำซ้อน พร้อมตัวอย่างการใช้งานจริง
สารบัญ
Utility Types คืออะไร
TypeScript มี built-in utility types ที่ช่วยแปลง type ที่มีอยู่แล้วให้ใช้งานได้หลากหลายขึ้น
Types ที่ใช้บ่อย
Partial<T>
ทำให้ทุก property เป็น optional
interface User {
id: number;
name: string;
email: string;
}
type PartialUser = Partial<User>;
// { id?: number; name?: string; email?: string }
Required<T>
ทำให้ทุก property เป็น required (ตรงข้ามกับ Partial)
type RequiredUser = Required<PartialUser>;
// { id: number; name: string; email: string }
Pick<T, K>
เลือกเฉพาะ properties ที่ต้องการ
type UserPreview = Pick<User, 'id' | 'name'>;
// { id: number; name: string }
Omit<T, K>
ตัด properties ที่ไม่ต้องการออก
type UserWithoutEmail = Omit<User, 'email'>;
// { id: number; name: string }
Record<K, V>
สร้าง object type จาก key และ value
type RolePermissions = Record<'admin' | 'user' | 'guest', boolean[]>;
Readonly<T>
ป้องกันการแก้ไข properties หลังสร้างแล้ว
const config: Readonly<{ host: string; port: number }> = {
host: 'localhost',
port: 3000,
};
// config.port = 4000; // Error: Cannot assign to 'port'
Exclude<T, U> และ Extract<T, U>
type Status = 'draft' | 'published' | 'archived';
type ActiveStatus = Exclude<Status, 'archived'>;
// 'draft' | 'published'
type FinalStatus = Extract<Status, 'published' | 'archived'>;
// 'published' | 'archived'
NonNullable<T>
ตัด null และ undefined ออกจาก union type
type MaybeString = string | null | undefined;
type DefiniteString = NonNullable<MaybeString>;
// string
ReturnType<T>
ดึง return type จาก function
function getUser() {
return { id: 1, name: 'Panupong' };
}
type User = ReturnType<typeof getUser>;
// { id: number; name: string }
มีประโยชน์มากเมื่อต้องการ type ของ return value โดยไม่ต้องประกาศ interface แยก
Parameters<T>
ดึง parameter types จาก function เป็น tuple
function createSlug(title: string, separator = '-'): string {
return title.toLowerCase().replace(/\s+/g, separator);
}
type CreateSlugParams = Parameters<typeof createSlug>;
// [title: string, separator?: string]
Awaited<T>
Unwrap Promise type (TypeScript 4.5+)
async function fetchUser(): Promise<{ id: number; name: string }> { ... }
type FetchResult = Awaited<ReturnType<typeof fetchUser>>;
// { id: number; name: string }
เมื่อไรใช้อะไร
| Utility | เหมาะกับ |
|---|---|
Partial | Form data, update payloads |
Required | Validated output types |
Readonly | Config objects, constants |
Pick | API response ที่ต้องการบาง field |
Omit | สร้าง DTO ที่ซ่อน sensitive fields |
Record | Map ของ enum keys ไปยังค่า |
Exclude | กรอง union ออก |
Extract | เลือกเฉพาะ union ที่ต้องการ |
NonNullable | ยืนยันว่าไม่ใช่ null/undefined |
ReturnType | ดึง type จาก function output |
Parameters | ดึง type จาก function input |
Awaited | Unwrap Promise ซ้อนกัน |
Compose หลาย Utilities เข้าด้วยกัน
// สร้าง type สำหรับ update API — ทุก field optional ยกเว้น id
type UpdateUserPayload = Partial<Omit<User, 'id'>> & Pick<User, 'id'>;
// ดึงเฉพาะ fields ที่เป็น string
type StringFields<T> = {
[K in keyof T as T[K] extends string ? K : never]: T[K];
};