TypeScript Modules Part 2


This is a continuation of TypeScript Modules blog post. Here we make a bit more complicated and change the example to make a calculator that computes a few volumes of a few basic shapes. We have an example of one module and one class that has four methods (functions). Some functions have more than one parameter. Let’s dive right into the code for this. Here we have two TypeScript files that we are compiling into one output file.

calculator.ts

/// <reference path="calcformulas.ts" />
var use = new Calculator.CalcVol();
console.log("Volume of a cube with sides of length 4 is: " + use.volCube(4));
console.log("Volume of a right circular cone with radius 3 and height 7: " + use.volRCCone(3, 7));
console.log("Volume of a cylinder with circumference 4.8 and height 5.8 is " + use.volCylinder(4.8, 5.8));

calcformulas.ts

module Calculator {

    export class CalcVol {
        volCube (n: number) { return n * n * n };
        // vol sphere = 4/3 pi r cubed
        volSphere (r : number) { 4 / 3 * Math.PI * Math.pow(r, 3) };
        // vol right circluar cone = pi r squared times height / 3
        volRCCone (r:number, h:number){
          return Math.PI * Math.pow(r, 2) * h / 3; }
        // circumference = pi * diameter = 2 pi r
        // r = c / ( 2 pi )
        volCylinder (c:number, h:number){  // c is circumference
          return h * Math.pow(c, 2) / Math.PI / 4
        }
    }
}

Series Navigation<< TypeScript Modules

Leave a comment

Your email address will not be published. Required fields are marked *