TypeScript utility types
TypeScript มี generic type สำเร็จรูปในตัว (global — ไม่ต้อง import) สร้างด้วย mapped/conditional type ที่เรียนไป
ปรับ modifier
interface User {
id: number;
name: string;
email: string;
}
Partial<User> // { id?: number; name?: string; email?: string }
Required<User> // ลบ ? ออกทุกตัว (ถ้ามี)
Readonly<User> // { readonly id: number; readonly name: string; ... }Partial — ใช้กับ update payload (แก้บาง field):
function updateUser(id: number, changes: Partial<User>) {
// changes มีแค่ field ที่ต้องแก้
}
updateUser(1, { name: "บอย" });เลือก / ตัด key
Pick<User, "id" | "name">
// { id: number; name: string }
Omit<User, "email">
// { id: number; name: string }Pick — สร้าง view ที่มีเฉพาะ field ที่ต้องการ (public user, DTO):
type PublicUser = Pick<User, "id" | "name">;Omit — ตัด field ที่ไม่อยาก expose (password, internal):
type SafeUser = Omit<User, "passwordHash" | "internalNotes">;Record — สร้าง object type
Record<string, number>
// { [key: string]: number }
Record<"admin" | "editor" | "viewer", Permission[]>
// { admin: Permission[]; editor: Permission[]; viewer: Permission[] }
const rolePermissions: Record<Role, string[]> = {
admin: ["read", "write", "delete"],
editor: ["read", "write"],
viewer: ["read"],
}; // TS บังคับให้มีครบทุก roleจัดการ union
Exclude<T, U> // เอา member ของ T ที่ assignable กับ U ออก
Extract<T, U> // เอาเฉพาะ member ของ T ที่ assignable กับ U
NonNullable<T> // เอา null และ undefined ออก
type Status = "active" | "inactive" | "pending" | "deleted";
Exclude<Status, "deleted"> // "active" | "inactive" | "pending"
Extract<Status, "active" | "pending" | "xyz"> // "active" | "pending"
NonNullable<string | null | undefined> // stringดึงจากฟังก์ชัน
function createOrder(userId: number, items: string[], express = false) {
return { id: crypto.randomUUID(), userId, items, express, createdAt: new Date() };
}
ReturnType<typeof createOrder>
// { id: string; userId: number; items: string[]; express: boolean; createdAt: Date }
Parameters<typeof createOrder>
// [userId: number, items: string[], express?: boolean]
// ดึง argument ตัวแรก
Parameters<typeof createOrder>[0] // numberReturnType<typeof fn> — ทำ type ของ object ที่ factory function สร้าง โดยไม่ต้องเขียน interface ซ้ำ
ดึงจาก Promise / async
Awaited<Promise<string>> // string
Awaited<Promise<Promise<number>>> // number (unwrap ทุกชั้น)
async function fetchUser(id: number): Promise<User> { /* ... */ }
type FetchedUser = Awaited<ReturnType<typeof fetchUser>>; // Userconstructor
class Widget {
constructor(public name: string, public size: number) {}
}
ConstructorParameters<typeof Widget> // [name: string, size: number]
InstanceType<typeof Widget> // Widgetstring manipulation
Uppercase<"hello"> // "HELLO"
Lowercase<"HELLO"> // "hello"
Capitalize<"hello"> // "Hello"
Uncapitalize<"Hello"> // "hello"
type EventName<T extends string> = `on${Capitalize<T>}`;
type ClickEvent = EventName<"click">; // "onClick"ประกอบ utility types
// update payload — field แก้ได้บางส่วน แต่ id บังคับ
type UpdatePayload = Partial<Omit<User, "id">> & Pick<User, "id">;
// { id: number; name?: string; email?: string }
// deep readonly แบบง่าย (recursive ต้องเขียนเอง)
type ReadonlyDeep<T> = {
readonly [K in keyof T]: T[K] extends object ? ReadonlyDeep<T[K]> : T[K];
};
// create input (ไม่มี field ที่ server สร้าง)
type CreateUserInput = Omit<User, "id" | "createdAt" | "updatedAt">;ตารางสรุป
| utility | ทำอะไร |
|---|---|
Partial<T> | ทุก property เป็น optional |
Required<T> | ทุก property เป็น required |
Readonly<T> | ทุก property เป็น readonly |
Pick<T, K> | เอาเฉพาะ key K |
Omit<T, K> | ตัด key K ออก |
Record<K, V> | { [P in K]: V } |
Exclude<T, U> | union T ลบ member ที่ตรง U |
Extract<T, U> | union T เอาเฉพาะที่ตรง U |
NonNullable<T> | ลบ null/undefined |
ReturnType<F> | return type ของ F |
Parameters<F> | tuple ของ argument types |
Awaited<T> | unwrap Promise |
InstanceType<C> | type ของ instance ที่ new C ได้ |
Uppercase/Lowercase/Capitalize | แปลง string literal |
เรื่องที่คนมักพลาด
Omitkey ที่ไม่มีจริง — TS 4.x ไม่ error (ต่างจากPickที่ error); ตั้งexactOptionalPropertyTypes/ ใช้ระวังPartial<T>แล้วส่งเข้า function ที่ต้องการ field ครบ —Partialทำให้ optional หมดRecord<string, T>แล้วเข้าถึง key ที่ไม่มี — ไม่เตือน (เว้นnoUncheckedIndexedAccess)ReturnType<fn>(ไม่มีtypeof) —fnเป็น value; ต้องReturnType<typeof fn>Exclude/Extractกับ object types — ทำงานกับ union member; object ทั้งอันเป็น 1 member- สร้าง
DeepPartialเอง — TS ไม่มีในตัว (มีแต่ shallowPartial); ต้องเขียน recursive Pick<T, K>โดย K ไม่ใช่ subset ของkeyof T— error
สรุป
- modifier:
Partial(optional),Required,Readonly - key:
Pick<T, K>(เอา),Omit<T, K>(ตัด) - object:
Record<K, V>— บังคับให้มี key ครบ (เมื่อ K เป็น union ของ literal) - union:
Exclude<T, U>,Extract<T, U>,NonNullable<T> - function:
ReturnType<typeof fn>,Parameters<typeof fn>,Awaited<T>,InstanceType - string:
Uppercase/Capitalize/… - ประกอบกันได้:
Partial<Omit<User, "id">> & Pick<User, "id">; deep versions เขียนเอง
จบเฟส type system core บทถัดไปเข้าเฟส class เริ่มที่ class — field, constructor, access modifier และ parameter properties