Nested namespace
- TypeScript course
- Intermediate
- Lesson 55/89
- 4 min
Learn nested namespaces.
Nested namespaces
Namespaces can be nested. With namespace Outer { export namespace Inner { ... } } you can export one namespace inside another. Members are accessed from outside as Outer.Inner.member via a dot chain.
namespace Dis {
export namespace Ic {
export function f() {
return "iç";
}
}
}
console.log(Dis.Ic.f()); // "iç"Each level must be exported
In nested namespaces, both the outer and inner namespace must be marked export to be accessible from outside. Otherwise the inner namespace is invisible from outside and the Outer.Inner.member access is a compile error.
Practice Apply the nested pattern
The compiled equivalent of a nested namespace structure can be expressed as a nested object pattern. Define an object Dis with an inner object Ic. Inside Ic, place a method f(): string with body return "iç". Call it from outside via the dot chain and print the result with console.log.
Starter code
// Dis adında bir nesne tanımla
// Ic adında iç nesne ekle
// f metodunu ekle, "iç" döndürsün
// f metodunu çağır, sonucu yazdırSample solution
const Dis = {
Ic: {
f(): string {
return "iç";
}
}
};
console.log(Dis.Ic.f());Expected output
iç
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 How is a member in a nested namespace accessed?
- Via import Ic from Dis
- Only as Ic.member
- As Dis::Ic::member
- Via the Dis.Ic.member dot chain Correct answer
Explanation: In a nested namespace, a member is accessed via the Dis.Ic.member dot chain. Ic.member alone does not work because Ic is not directly visible from outside; :: is C++ syntax; import is for module imports.
2 Access the inner namespace
namespace Dis {
export namespace Ic {
export function f(): string {
return "iç";
}
}
}
console.log(Dis.____.f());
namespace Dis {
export namespace Ic {
export function f(): string {
return "iç";
}
}
}
console.log(Dis.Ic.f());
Explanation: In the Dis.Ic.f() call, the inner namespace name Ic is used. Ic.f forms a wrong double access; f alone does not name the function path; Dis is already the first outer step.
3 Nested namespace parts
| Term | Meaning |
|---|---|
export namespace Ic |
Inner namespace export |
namespace Dis |
Outer namespace declaration |
Dis.Ic.f() |
Call via dot chain |
her seviye export |
Visibility rule for nesting |