Software Design Principles
AllInOne TypeScript TutorialSetupTypeSystem : VariablesOparators:Expression:Conditions and loopsFunctions.Class Object and Interfaces.Module and NameSpaces:Polymorphisms with design paterns.
AllInOne TypeScript Tutorial
Setup
npm install -g typescript // write file function greeter(person) { return "Hello, " + person; } // compile: tsc greeter.ts // Execute: The result will be a file greeter.js which contains the same JavaScript that you fed in.
TypeSystem : Variables
// define: let isDone: boolean = false; let decimal: number = 6; let hex: number = 0xf00d; let binary: number = 0b1010; let octal: number = 0o744; //TypeScript also uses double quotes (") or single quotes (') to surround string data. let color: string = "blue"; //array let list: number[] = [1, 2, 3]; let list: Array<number> = [1, 2, 3]; // touple: let x: [string, number]; // Initialize it x = ["hello", 10]; // OK // Initialize it incorrectly x = [10, "hello"]; // Error // enum enum Color {Red, Green, Blue} let c: Color = Color.Green; enum Color {Red = 1, Green = 2, Blue = 4} let c: Color = Color.Green; // Any for dynamic contents let notSure: any = 4; notSure = "maybe a string instead"; notSure.ifItExists(); // okay, ifItExists might exist at runtime notSure.toFixed(); // okay, toFixed exists (but the compiler doesn't check) // void: void is a little like the opposite of any: the absence of having any type at all. function warnUser(): void { console.log("This is my warning message"); } // undefined and null. let u: undefined = undefined; let n: null = null; // never: never is the return type for a function expression or an arrow function expression that always throws an exception or one that never returns; function error(message: string): never { throw new Error(message); } // let vs var: -> many common problems in JavaScript are alleviated by using let, so you should use it instead of var whenever possible. // Union Types. var val:string|number val = 12 val = "This is a string" var arr:number[]|string[]; // takes string or string array. function disp(name:string|string[]) { if(typeof name == "string") { console.log(name) } else { var i; for(i = 0;i<name.length;i++) { console.log(name[i]) } } }
Oparators:
// Arithmetic operators: +, -, *, /, %, ++, -- // Logical operators: >,<,>=,<= // Relational operators: &&, ||, ! // Bitwise operators: &, |, ^, ~, >>,<< // Assignment operators: =, +=, -= // Ternary/conditional operator: var result = num > 0 ?"positive":"non-positive" // String operator var msg:string = "hello"+"world" // Type Operator var num = 12; console.log(typeof num); //output: number
Expression:
// embedded expressions are of the form ${ expr }. let sentence: string = `Hello, my name is ${ fullName }.
Conditions and loops
  1. Condition ops are same as C, if, if-else, if-else if - else, switch-case
  2. loop as same as C, while() and for(...), they also have break and continue.
Functions.
* Same as C, But it supports optinal params, defulat arguments.
* Same as C, But it supports optinal params, defulat arguments.
// optinal function disp_details(id:number,name:string,mail_id?:string) { ... } disp_details(123,"John"); disp_details(111,"mary","mary@xyz.com"); // veriable arguments function addNumbers(...nums:number[]) { var i; var sum:number = 0; for(i = 0;i<nums.length;i++) { sum = sum + nums[i]; } console.log("sum of the numbers",sum) } addNumbers(1,2,3) addNumbers(10,10,10,10,10) // default arguments function calculate_discount(price:number,rate:number = 0.50) { var discount = price * rate; console.log("Discount Amount: ",discount); } calculate_discount(1000) calculate_discount(1000,0.30) // Annomous function. var msg = function() { return "hello world"; } console.log(msg()) // Function type and Expression. var myFunction = new Function("a", "b", "return a * b"); var x = myFunction(4, 3); console.log(x); // Lamda functions: ( [param1, parma2,…param n] )=>statement; var foo = (x:number)=> { x = 10 + x console.log(x) } foo(100) // optinal parenthesi in case of signal parmas. var display = x=> { console.log("The function got "+x) } display(12) // function overloading: function disp(s1:string):void; function disp(n1:number,s1:string):void; function disp(x:any,y?:any):void { console.log(x); console.log(y); } disp("abc") disp(1,"xyz");
Class Object and Interfaces.
* class: TypeScript supports object-oriented programming features like classes, interfaces, etc.
class Car { //field _engine:string; //constructor constructor(engine:string) { this._engine = engine } //function disp():void { console.log("Engine is : "+this._engine) } } //create an object var obj = new Car("XXSY1") //access the field console.log("Reading attribute value Engine as : "+obj.engine) //access the function obj.disp()
* Class Inheritance:
class Shape { Area:number constructor(a:number) { this.Area = a } } class Circle extends Shape { disp():void { console.log("Area of the circle: "+this.Area) } } var obj = new Circle(223); obj.disp()
* Method Overloading.
class PrinterClass { doPrint():void { console.log("doPrint() from Parent called…") } } class StringPrinter extends PrinterClass { doPrint():void { super.doPrint() console.log("doPrint() is printing a string…") } } var obj = new StringPrinter() obj.doPrint()
* static member:
class StaticMem { static num:number; static disp():void { console.log("The value of num is"+ StaticMem.num) } } StaticMem.num = 12 // initialize the static variable StaticMem.disp() // invoke the static method
* Visibility using private, public and protected:
class Encapsulate { str:string = "hello" private str2:string = "world" } var obj = new Encapsulate() console.log(obj.str) //accessible console.log(obj.str2) //compilation Error as str2 is private
* An interface is a syntactical contract that an entity should conform to. In other words, an interface defines the syntax that any entity must adhere to.
interface IPerson { firstName:string, lastName:string, sayHi: ()=>string } var customer:IPerson = { firstName:"Tom", lastName:"Hanks", sayHi: ():string =>{return "Hi there"} }
* Interfaces and Inheritance:
interface Person { age:number } interface Musician extends Person { instrument:string } interface Child extends IParent1, IParent2 { }
* class with interface.
Module and NameSpaces:
* A namespace definition begins with the keyword namespace followed by the namespace name as follows
FileName :IShape.ts ---------- namespace Drawing { export interface IShape { draw(); } }
*module: A module is designed with the idea to organize code written in TypeScript. Modules are broadly divided into −Internal Modules and External Modules
Polymorphisms with design paterns.
// IShape.ts export interface IShape { draw(); } // Circle.ts import shape = require("./IShape"); <<< This is replaced by // import {shape} from "./IShape" export class Circle implements shape.IShape { public draw() { console.log("Cirlce is drawn (external module)"); } } // Triangle.ts import shape = require("./IShape"); export class Triangle implements shape.IShape { public draw() { console.log("Triangle is drawn (external module)"); } } // TestShape.ts import shape = require("./IShape"); import circle = require("./Circle"); import triangle = require("./Triangle"); function drawAllShapes(shapeToDraw: shape.IShape) { shapeToDraw.draw(); } drawAllShapes(new circle.Circle()); drawAllShapes(new triangle.Triangle());