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

TypeScript Declaration Merging — ต่อเติม type ที่มีอยู่

Declaration merging รวม declarations ที่มีชื่อเดียวกันเข้าด้วยกัน — ใช้ขยาย interface หรือ module type ที่มาจาก library

Interface merging — เพิ่ม property ได้โดยไม่ต้องแก้ต้นฉบับ:

// lib.d.ts (จาก library)
interface Window {
  fetch: typeof fetch;
}

// globals.d.ts (เพิ่มเอง)
interface Window {
  __APP_VERSION__: string;  // merged เข้ากับ Window
  analytics: Analytics;
}

// ใช้ได้เลย — TypeScript รู้ว่ามี __APP_VERSION__
console.log(window.__APP_VERSION__);

Module augmentation — ขยาย type จาก package:

// astro.d.ts — เพิ่ม locals type สำหรับ Astro middleware
declare namespace App {
  interface Locals {
    user: { id: string; name: string } | null;
    theme: 'light' | 'dark';
  }
}

จากนั้น Astro.locals.user จะมี type ที่ถูกต้องในทุก Astro page

ข้อจำกัด: class ไม่รองรับ merging — ใช้ได้แค่กับ interface และ namespace