YouTip LogoYouTip

Ts Namespace

## IShape.ts File Code: ```typescript namespace Drawing{ export interface IShape{ draw(); } } ## Circle.ts File Code: ```typescript /// namespace Drawing{ export class Circle implements IShape{ public draw(){ console.log("Circle is drawn"); } } } ## Triangle.ts File Code: ```typescript /// namespace Drawing{ export class Triangle implements IShape{ public draw(){ console.log("Triangle is drawn"); } } } ## TestShape.ts File Code: ```typescript /// /// /// function drawAllShapes(shape:Drawing.IShape){ shape.draw(); } drawAllShapes(new Drawing.Circle()); drawAllShapes(new Drawing.Triangle()); Compile the above code using the `tsc` command: ```bash tsc --out app.js TestShape.ts The resulting JavaScript code is: ## JavaScript ```javascript /// var Drawing; (function(Drawing){ var Circle = /** @class */(function(){ function Circle(){} Circle.prototype.draw = function(){ console.log("Circle is drawn"); }; return Circle; }()); Drawing.Circle = Circle; })(Drawing || (Drawing = {})); /// var Drawing; (function(Drawing){ var Triangle = /** @class */(function(){ function Triangle(){} Triangle.prototype.draw = function(){ console.log("Triangle is drawn"); }; return Triangle; }()); Drawing.Triangle = Triangle; })(Drawing || (Drawing = {})); /// /// /// function drawAllShapes(shape){ shape.draw(); } drawAllShapes(new Drawing.Circle()); drawAllShapes(new Drawing.Triangle()); Use the `node` command to view the output: ```bash $ node app.js Circle is drawn Triangle is drawn * * * ## Nested Namespaces Namespaces support nesting, meaning you can define a namespace inside another namespace. ```typescript namespace namespace_name1{ export namespace namespace_name2{ export class class_name{} } } Member access is achieved using the dot `.` operator, as shown in the following example: ## Invoice.ts File Code: ```typescript namespace { export namespace invoiceApp{ export class Invoice{ public calculateDiscount(price: number){ return price * .40; } } } } ## InvoiceTest.ts File Code: ```typescript /// var invoice = new .invoiceApp.Invoice(); console.log(invoice.calculateDiscount(500)); Compile the above code using the `tsc` command: ```bash tsc --out app.js InvoiceTest.ts The resulting JavaScript code is: ```javascript /// var ; (function(){ var invoiceApp; (function(invoiceApp){ var Invoice = /** @class */(function(){ function Invoice(){} Invoice.prototype.calculateDiscount = function(price){ return price * .40; }; return Invoice; }()); invoiceApp.Invoice = Invoice; })(invoiceApp = .invoiceApp || (.invoiceApp = {})); })( || ( = {})); /// var invoice = new .invoiceApp.Invoice(); console.log(invoice.calculateDiscount(500)); Use the `node` command to view the output: ```bash $ node InvoiceTest.js 200
← Ts AmbientTs Class β†’