Using namespace we can group logically related code. This is built into typescript, unlike javascript. A namespace can include classes, interfaces, functions, and variables.
We can create a namespace in typescript using namespace
keyword followed by any valid name.
For Example:
namespace MyNamespace { }
If we want the members of the namespace to be accessed outside the namespace then we need to mark those members with the export
keyword.
TypeScript Namespace Example
namespace MyNamespace { export interface IStudent { ... } export class Student { ... } }
In order to access the class Student in another namespace, we need to follow the syntax:
MyNamespace.Student
If the namespace is in a separate TypeScript file, then it should be referenced using triple-slash reference syntax.
/// <reference path = "Student.ts" />
Compile Namespace
To compile a typescript namespace and generate a single .js file, we use --outFile
command.
tsc --outFile MyNamespace.js MyNamespace.ts
That’s all about namespace in typescript. We will learn about Typescript Modules in the next section.