Summary - Namespaces
- TypeScript course
- Intermediate
- Lesson 57/89
- 4 min
Write a legacy-style library header with namespaces.
Summary - Namespaces
Namespaces are the legacy pattern for grouping related code in the global scope. They are declared with namespace Name, members are exported with export, they can be nested, and accessed as Outer.Inner.member. Modern projects prefer modules; namespaces are still useful for porting legacy libraries.
namespace Kutuphane {
export namespace Matematik {
export function topla(a, b) { return a + b; }
}
}
Kutuphane.Matematik.topla(2, 3);Practice Legacy-style library header
Using the nested object pattern that is the compiled equivalent of a nested namespace structure, define an object Kutuphane with an inner object Matematik. Inside Matematik, place methods topla(a: number, b: number): number and carp(a: number, b: number): number; topla returns a + b, carp returns a * b. Call them from outside via the dot chain with 2 and 3, printing the results on separate lines.
Starter code
// Kutuphane adında bir nesne tanımla
// Matematik adında iç nesne ekle
// topla metodunu ekle, a+b döndürsün
// carp metodunu ekle, a*b döndürsün
// her ikisini de 2 ve 3 ile çağır, sonuçları ayrı satırda yazdırSample solution
const Kutuphane = {
Matematik: {
topla(a: number, b: number): number {
return a + b;
},
carp(a: number, b: number): number {
return a * b;
}
}
};
console.log(Kutuphane.Matematik.topla(2, 3));
console.log(Kutuphane.Matematik.carp(2, 3));Expected output
5 6
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 In which case might a namespace be preferred over a module?
- When starting a modern web application
- When writing an ES-module-compatible library
- When writing a single-file utility Correct answer
- When setting up a new multi-file project
Explanation: For single-file utilities, namespaces can still be practical. For multi-file new projects, modern web apps, and ES-module libraries, modules are preferred.
2 Access with the outer namespace name
namespace Kutuphane {
export namespace Matematik {
export function topla(a: number, b: number): number {
return a + b;
}
}
}
console.log(____.Matematik.topla(2, 3));
namespace Kutuphane {
export namespace Matematik {
export function topla(a: number, b: number): number {
return a + b;
}
}
}
console.log(Kutuphane.Matematik.topla(2, 3));
Explanation: Access starts with the outermost namespace name; that is why we write console.log(Kutuphane.Matematik.topla(...)). Matematik is the inner namespace; Hesap and Dis are undefined in this context.
3 Match namespace concepts
| Term | Meaning |
|---|---|
namespace Ad |
Global scope grouping |
export namespace Ic |
Inner namespace export |
Dis.Ic.üye |
Dot chain access |
modern projelerde module |
Modern recommendation |