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

Category: reference

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

รวม Utility Types ใน TypeScript ที่ช่วยลดการเขียน type ซ้ำซ้อน พร้อมตัวอย่างการใช้งานจริง

· อ่านประมาณ 2 นาที

สารบัญ

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เหมาะกับ
PartialForm data, update payloads
RequiredValidated output types
ReadonlyConfig objects, constants
PickAPI response ที่ต้องการบาง field
Omitสร้าง DTO ที่ซ่อน sensitive fields
RecordMap ของ enum keys ไปยังค่า
Excludeกรอง union ออก
Extractเลือกเฉพาะ union ที่ต้องการ
NonNullableยืนยันว่าไม่ใช่ null/undefined
ReturnTypeดึง type จาก function output
Parametersดึง type จาก function input
AwaitedUnwrap 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];
};