Namespaces

We can create namespaces in TypeScript using the namespace keyword, as illustrated. All the classes defined under namespace will be scoped under that particular namespace and will not be attached to the global scope:

namespace Inventory { 
Class Product {
constructor (public name: string, public quantity: number) { }
}
// product is accessible
var p = new Product('mobile', 101);
}
// Product class is not accessible outside namespace
var p = new Inventory.Product('mobile', 101);

To make the Product class available outside the namespace, we need to add an export keyword when defining the Product class, as follows:

namespace Inventory { 
export Class Product {
constructor (public name: string, public quantity: number) { }
}
}
// Product class is now accessible outside Inventory namespace
var p = new Inventory.Product('mobile', 101);

We can also share the namespace across files by adding a reference statement at the beginning of the code in the referring files, as shown:

/// <reference path="Inventory.ts" /> 
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset