Skip to content

Type Operations (การดำเนินการกับ type)

เครื่องมือสำหรับจัดการและแปลง type ข้อมูลใน TypeScript ที่ช่วยให้เราสามารถสร้างและปรับแต่ง type ได้อย่างยืดหยุ่น

Generics (เจเนอริก)

สร้างคอมโพเนนต์ที่ทำงานกับหลาย type โดยไม่ต้องระบุ type ที่แน่นอน

ts
// ฟังก์ชัน identity ที่รับ type ใดก็ได้และคืนค่า type นั้นกลับมา
function identity<T>(arg: T): T {
  return arg;
}

// ใช้งานกับ string
let output = identity<string>("hello");

// ใช้งานกับ number
let numberOutput = identity<number>(42);

// TypeScript สามารถ infer type ให้ได้โดยไม่ต้องระบุ
let inferred = identity("world"); // type เป็น string อัตโนมัติ

ประโยชน์ของ Generics:

  • เขียนโค้ดที่ใช้ซ้ำได้กับหลาย type
  • ยังคงความปลอดภัยของ type
  • ลดความซ้ำซ้อนของโค้ด

Utility Types (เครื่องมือช่วยจัดการ type)

TypeScript มี Utility Types ที่ช่วยจัดการ type ให้สะดวกขึ้น

ts
interface Todo {
  title: string;
  description: string;
  completed: boolean;
  createdAt: Date;
}

// Pick: เลือกบาง properties จาก type
// เหมาะสำหรับเมื่อต้องการใช้บางส่วนของ object
type TodoPreview = Pick<Todo, "title" | "completed">;

// Partial: ทำให้ทุก property เป็น optional
// ใช้เมื่อต้องการสร้าง object ทีละส่วน
type PartialTodo = Partial<Todo>;

// Omit: ละเว้นบาง properties
// ใช้เมื่อต้องการเอาบาง field ออก
type TodoWithoutDescription = Omit<Todo, "description">;

// Readonly: ทำให้ทุก property เป็น readonly
// ใช้เมื่อต้องการป้องกันการเปลี่ยนแปลง
type ReadonlyTodo = Readonly<Todo>;

Mapped Types (การแปลง type)

สร้าง type ใหม่โดยแปลงคุณสมบัติของ type ที่มีอยู่

ts
// สร้าง type ที่ทำให้ทุก property เป็น optional
type Optional<T> = {
  [P in keyof T]?: T[P];
};

// สร้าง type ที่ทำให้ทุก property เป็น readonly
type Readonly<T> = {
  readonly [P in keyof T]: T[P];
};

interface Book {
  title: string;
  author: string;
  pages: number;
}

// ใช้งาน mapped types
type OptionalBook = Optional<Book>;
type ReadonlyBook = Readonly<Book>;

// ตัวอย่างการใช้งานจริง
function updateBook(book: OptionalBook) {
  // สามารถส่งเฉพาะ field ที่ต้องการอัปเดต
}

Conditional Types (เงื่อนไขกับ type)

สร้าง type ที่มีเงื่อนไขเหมือน if-else

ts
type IsString<T> = T extends string ? true : false;

type A = IsString<string>; // true
type B = IsString<number>; // false

// ตัวอย่างใช้งานกับฟังก์ชัน
type ReturnType<T> = T extends (...args: any[]) => infer R ? R : never;

function getUser() {
  return { name: "John", age: 30 };
}

type User = ReturnType<typeof getUser>; // { name: string; age: number }

Template Literal Types (type แบบ template string)

สร้าง type จาก template string

ts
type EventName = "click" | "scroll" | "mousemove";
type EventHandler = `on${Capitalize<EventName>}`;
// ได้ type: "onClick" | "onScroll" | "onMousemove"

// ใช้งานกับฟังก์ชัน
function addEventListener(
  event: EventName,
  handler: (e: Event) => void,
) {
  // ...
}