Concept Flow - Namespace declaration
Start
Declare Namespace
Add Variables/Functions/Classes
Access Members with Namespace
Use in Code
End
This flow shows how a namespace is declared, members are added, and then accessed using the namespace name.
namespace MySpace {
export const greeting = "Hello";
export function sayHi() {
return greeting + ", world!";
}
}
console.log(MySpace.sayHi());| Step | Action | Evaluation | Result |
|---|---|---|---|
| 1 | Declare namespace MySpace | Namespace created | MySpace namespace exists |
| 2 | Add exported const greeting | greeting = "Hello" | MySpace.greeting = "Hello" |
| 3 | Add exported function sayHi | Function defined | MySpace.sayHi() available |
| 4 | Call MySpace.sayHi() | Execute function | Returns "Hello, world!" |
| 5 | console.log output | Print returned string | Output: Hello, world! |
| Variable | Start | After Declaration | After Assignment | Final |
|---|---|---|---|---|
| MySpace | undefined | namespace object created | greeting and sayHi added | MySpace with greeting and sayHi |
| MySpace.greeting | undefined | undefined | "Hello" | "Hello" |
| MySpace.sayHi | undefined | undefined | function | function |
Namespace declaration syntax:
namespace Name {
export const/let/var/function/class ...
}
- Use 'export' to make members accessible outside.
- Access members with NamespaceName.member.
- Helps organize code and avoid name conflicts.namespace in TypeScript?Utils in TypeScript?namespace to declare namespaces.namespace Name { }, so namespace Utils { } is correct.namespace MathOps {
export function add(a: number, b: number) {
return a + b;
}
}
console.log(MathOps.add(3, 4));add is inside namespace MathOps and is exported, so it can be accessed outside.MathOps.add(3, 4) returns 3 + 4 = 7.namespace Data {
function getData() {
return "info";
}
}
console.log(Data.getData());getData is declared but not exported, so it's private to the namespace.getData is not exported, it cannot be accessed outside the namespace, causing an error.log function from Logger inside App?namespace Logger {
export function log(message: string) {
console.log("LOG: " + message);
}
}
namespace App {
export function run() {
// Call Logger.log here
}
}
App.run();Logger.log is correct.Logger.log("App started") correctly calls the exported function from the Logger namespace.Pass the test and this pattern moves unknown