Namespace के Basics
In this page:
namespace NamespaceName {
export const value = expression;
export function name(): type {}
}
NamespaceName.name();
एक Namespace बनाना
Related declarations के लिए एक named container बनाने के लिए namespace keyword उपयोग करें, उन्हें separate files या एक ES module system की ज़रूरत के बिना एक single accessible name के under group करते हुए।
उदाहरण: Creating a Namespace
namespace Shapes {
export function area(side: number) {
return side * side;
}
}
console.log(Shapes.area(4));
Namespace Members Export करना
Namespace के अंदर members को इससे export किया जाना चाहिए अगर namespace के बाहर का code इन्हें access करना चाहे, यह mirror करते हुए कि modules अपनी own boundary के बाहर क्या visible है control करते हैं।
उदाहरण: Exporting Namespace Members
namespace MathUtils {
export const PI = 3.14159;
function internalHelper() { return "hidden"; }
}
console.log(MathUtils.PI);
Nested Namespaces
Namespaces दूसरे namespaces रख सकते हैं, related declarations को deeper, more specific groupings में nest करते हुए, similar कि कैसे packages दूसरे packages के अंदर nested हो सकते हैं। Deeply nested namespaces dotted paths से access किए जाते हैं, जैसे Outer.Inner.member।
उदाहरण: Nested Namespaces
namespace Outer {
export namespace Inner {
export const value = 42;
}
}
console.log(Outer.Inner.value);
Classes के साथ Namespaces
Classes namespaces से export की जा सकती हैं और फिर namespace name के through access की जा सकती हैं, एक namespace को related classes, interfaces, और functions को एक umbrella के under bundle करने देते हुए।
उदाहरण: Namespaces with Classes
namespace Shapes {
export class Circle {
constructor(public radius: number) {}
}
}
const c = new Shapes.Circle(5);
console.log(c.radius);
Namespaces and Modern Modules
Namespaces एक older TypeScript organization mechanism है जो widespread ES module support से पहले का है; modern applications के लिए, ES modules code organize करने का recommended तरीका हैं।
उदाहरण: Namespaces and Modern Modules
// Older style:
namespace Legacy {
export const value = 1;
}
// Modern style (recommended):
// export const value = 1;
console.log(Legacy.value);
- एक namespace member पर
exportभूल जाना और फिर बाहरMathUtils.internalHelperउपयोग करते समय एक error पाना। - एक file में
namespaceकोimport/exportके साथ mix करना, तो namespace global होने के बजाय एक module के लिए local बन जाता है। - नए code में namespaces उपयोग करना जब ES modules preferred तरीका हैं, और यह देखकर surprised होना कि वे runtime पर एक object emit करते हैं।
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: