Declaration merging คือการที่ TypeScript รวมหลายประกาศที่มีชื่อเดียวกันเข้าเป็นนิยามเดียว Interfaces, namespaces และการสร้างอื่นๆ บางรูปแบบจะรวมอัตโนมัติ
Interface merging
interface Box { width: number; }
interface { : ; }
Declaration merging คือการที่ TypeScript รวมหลายประกาศที่มีชื่อเดียวกันเข้าเป็นนิยามเดียว Interfaces, namespaces และการสร้างอื่นๆ บางรูปแบบจะรวมอัตโนมัติ
interface Box { width: number; }
interface { : ; }
นี่คือวิธีที่คุณเพิ่มประเภทให้กับไลบรารีหรือ globals ที่คุณไม่ได้เป็นเจ้าของ:
// Add a custom property to Express's Request
declare global {
namespace Express {
interface Request { user?: { id: string }; } // merges into Express.Request
}
}
request.user; // ✅ now typed everywhere
// Augment a module
declare module "some-lib" {
interface Options { newOption: boolean; }
}
เนื่องจาก Request/Options ของไลบรารีเป็น interface การประกาศของคุณจึงรวมเข้าไปแทนที่จะขัดแย้ง — ซึ่งช่วยให้คุณสามารถขยายประเภทที่คุณไม่สามารถแก้ไขได้อย่างปลอดภัย
function greet() {}
namespace greet { export const version = "1.0"; }
greet.version; // "1.0" — namespace merged onto the function
type ถึงทำไม่ได้type A = { x: number };
type A = { y: number }; // ❌ Error: duplicate identifier
Type aliases เป็นเอกลักษณ์เฉพาะ; เพียง interfaces (และ namespaces) เท่านั้นที่จะรวมกัน — เหตุผลหลักในการใช้ interface สำหรับรูปร่าง API สาธารณะที่ขยายได้
Declaration merging คือกลไกเบื้องหลังmodule augmentation — ขยาย Express requests, เพิ่ม window, ปรับแต่งประเภทไลบรารี, ระบบธีม
เป็นความรู้ที่จำเป็นสำหรับการเขียนประเภทของแอปจริง โดยคุณต้องปรับประเภทที่คุณไม่สามารถควบคุมได้ โดยไม่ต้องแยกออกจากกัน