Declaration merging भनेको TypeScript ले एउटै नामको बहुविध declarations लाई एकल definition मा जोडिन सक्नु हो। Interfaces, namespaces, र केही अन्य constructs स्वचालित रूपमा merge हुन्छन्।
Interface merging
interface Box { : ; }
{ : ; }
Declaration merging भनेको TypeScript ले एउटै नामको बहुविध declarations लाई एकल definition मा जोडिन सक्नु हो। Interfaces, namespaces, र केही अन्य constructs स्वचालित रूपमा merge हुन्छन्।
interface Box { : ; }
{ : ; }
यो तरिका तपाईंले स्वामित्व नगरेको libraries वा globals मा types थप्न सक्नु हो:
// 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; }
}
Library को Request/Options एक interface भएकोले, तपाईंको declaration यसमा merge हुन्छ conflicting हुँदैन — तपाईंले edit गर्न सक्नु नभएको types लाई सुरक्षित रूपमा extend गर्न दिन्छ।
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) मात्र merge हुन्छन् — यो extensible public API shapes को लागि interface प्रयोग गर्ने मुख्य कारण हो।
Declaration merging module augmentation को पछाडि रहेको संयन्त्र हो — Express requests extend गर्ने, window मा थप्ने, library types customize गर्ने, theming systems।
यो वास्तविक apps लाई type गर्न आवश्यक ज्ञान हो जहाँ तपाईंले types adapt गर्नु पर्छ जुन तपाईंको नियन्त्रणमा छैन, उनीहरूलाई fork गरिएको बिना।