Declaration Merging की जानकारी
In this page:
interface Name {
property1: type;
}
interface Name {
property2: type;
}
Interfaces Merge करना
एक ही नाम से declared दो interfaces TypeScript द्वारा automatically merge हो जाती हैं, तो इनके members एक दूसरे को silently overwrite करने के बजाय एक single effective interface में combine हो जाते हैं।
उदाहरण: Merging Interfaces
interface Box {
height: number;
}
interface Box {
width: number;
}
const b: Box = { height: 10, width: 20 };
console.log(b);
Interface Methods Merge करना
Interface declarations merged result में properties के साथ-साथ methods भी contribute कर सकती हैं, तो एक interface की definition को कई declarations में split करने पर भी एक complete combined shape बनती है।
उदाहरण: Merging Interface Methods
interface Logger {
log(msg: string): void;
}
interface Logger {
warn(msg: string): void;
}
const logger: Logger = {
log: (msg) => console.log(msg),
warn: (msg) => console.log("WARN:", msg),
};
logger.warn("careful");
Namespace Merging
एक ही नाम share करने वाली Namespace declarations भी merge हो सकती हैं, related members को codebase में एक से ज़्यादा जगह से incrementally एक namespace में जोड़ने देते हुए।
उदाहरण: Namespace Merging
namespace Utils {
export const a = 1;
}
namespace Utils {
export const b = 2;
}
console.log(Utils.a, Utils.b);
Namespace and Class Merging
एक namespace एक ही नाम वाली class declaration के साथ merge हो सकता है, exported namespace members को उस class से attached static-like properties की तरह act करने देते हुए।
उदाहरण: Namespace and Class Merging
class Album {
constructor(public title: string) {}
}
namespace Album {
export const defaultTitle = "Untitled";
}
console.log(Album.defaultTitle);
Merging and Type Safety
Declaration merging अब भी TypeScript के normal type checking rules follow करता है; हर merged declaration के सभी required members को आखिरकार satisfy किया जाना चाहिए जहां भी merged type उपयोग हो।
उदाहरण: Merging and Type Safety
interface Config {
host: string;
}
interface Config {
port: number;
}
const config: Config = { host: "localhost", port: 8080 };
console.log(config);
- एक ही नाम से दो
typealiases declare करना और उनके merge होने की उम्मीद करना, जब सिर्फinterfacedeclarations merge होती हैं और type aliases एक duplicate identifier error देती हैं। - merged interface members को conflicting types देना, जैसे
height: numberऔरheight: string, जो एक error है। - यह भूल जाना कि एक merged interface को सभी members चाहिए, तो सिर्फ
heightवाला एक object literalBoxsatisfy करने में fail होता है।
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: