1 2 3 4 5 6 | // Single line comment /* Multi line comment Over 2 lines */ |
1 2 3 4 5 | // Tyepscript Compiler tsc // Options |
1 2 3 4 5 6 7 8 9 10 11 | // Types Number number Double precision 64-bit floating point values. It can be used to represent both, integers and fractions. String string Represents a sequence of Unicode characters Boolean boolean Represents logical values, true and false Void void Used on function return types to represent non-returning functions Null null Represents an intentional absence of an object value. Undefined undefined Denotes value given to all uninitialized variables // undefined means that the variable has no value or object assigned to it // null means that the variable has been set to an object whose value is undefined |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | // Variables var name:string = ”mary”; // Variable of type string assigned value var name:string; // Variable of type string, value is undefined var name = ”mary”; // Variable type is inferred as string, value assigned var name; // Variable type is any, value is undefined var name:string = "John"; var score1:number = 50; var score2:number = 42.50 var sum = score1 + score2 var str = '1' var str2:number = <number> <any> str; //str is now of type number |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | // Operators // Arithmetic a + b a - b a * b a / b a % b a++ b-- // Relational a > b a >= b a < b a <= b a == b a != b // Logical a && b a || b !(a && b) // Bitwise a & b a | b a ^ b ~b a << 1 a >> 1 a >>> 1 // Assignment a = a + b a += b a -= b a *= b a /= b |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 | // Decisions // If var num:number = 5 if (num > 0) { console.log("number is positive") } // If Else var num:number = 12; if (num % 2==0) { console.log("Even"); } else { console.log("Odd"); } // Nested If var num:number = 2 if(num > 0) { console.log(num+" is positive") } else if(num < 0) { console.log(num+" is negative") } else { console.log(num+" is neither positive nor negative") } // Switch var grade:string = "A"; switch(grade) { case "A": { console.log("Excellent"); break; } case "B": { console.log("Good"); break; } case "C": { console.log("Fair"); break; } case "D": { console.log("Poor"); break; } default: { console.log("Invalid choice"); break; } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 | // Loops // For var num:number = 5; var i:number; var factorial = 1; for(i = num;i>=1;i--) { factorial *= i; } // While var num:number = 5; var factorial:number = 1; while(num >=1) { factorial = factorial * num; num--; } // do while var n:number = 10; do { console.log(n); n--; } while(n>=0); // Break var i = 1; while (i <= 10) { if (i % 5 == 0) { console.log("The first multiple of 5 between 1 and 10 is : " + i); break; //exit the loop if the first multiple is found } i++; } //outputs 5 and exits the loop // Continue var num:number = 0 var count:number = 0; for(num=0;num<=20;num++) { if (num % 2==0) { continue } count++ } // Infinite Loops for(;;) { //statements } while(true) { //statements } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 | // Functions // Defining function myFunc () { //function definition console.log("function called") } // Calling myFunc(); // Returning function sayHello():string { //the function returns a string return "Hello World" } // Parameterised function test_param(n1:number, s1:string) { console.log(n1) console.log(s1) } // Non-primitive are passed into a function by reference, // which means that the reference to the object passed in // as the argument is passed into the function. // The copy of the content is not made for the argument and // the passed in object is modified directly // Optional Parameters // Marked optional by appending a question mark to its name. function function_name (param1[:type], param2[:type], param3?[:type]) function optionalFunc(param1 :string, param2 :int, optional? :string) { if ( optional === undefined ) { do_something(param1, param2) } else { do_something_else(param1, param2, param3) } // Rest Parameters // Must all be of the same type function restFunc1(...nums:number[]) {...} function restFunc2(name :string, ...nums:number[]) {...} // Default Parameters function defFunction(name:string, age:number = 21) { ... } // Anonymous Function var msg = function() { return "hello world"; } console.log(msg()) var res = function(a:number,b:number) { return a*b; }; console.log(res(12,2)) // Function Constructor var myFunction = new Function("a", "b", "return a * b"); var x = myFunction(4, 3); console.log(x); // Lambda Functions var doubleIt = (x:number)=> x * x console.log(doubeIt(4); // => 8 var doubleIt = (x:number)=> { x * x } console.log(doubeIt(4); // => 8 // Optional parentheses for a single parameter var func = (x)=> { // Do something with x } // Optional braces for a single statement var func = (x) => { // Do something with x } // Empty parentheses for no parameter var func = () => { // Do something } var func = function () => { // Do something with x } // Function Overloads function disp(v:string):void; // Data Types function disp(v:number):void; function disp(v:string):void; // Number of Parameters function disp(v:string, w:number):void; function disp(v:string, w:number):void; // Order of parameters function disp(w:number, v:string):void; // Order of parameters |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | // Numbers var var_name = new Number(value) Number.MAX_VALUE Number.MIN_VALUE Number.NaN Number.NEGATIVE_INFINITY Number.POSITIVE_INFINITY Number.prototype Number.constructor var myNum = Number (42) myNum.toExponential() myNum.toFixed() myNum.toLocaleString() myNum.toPrecision() myNum.toString() myNum.valueOf() |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | // Strings var myString = new String("Hello, World"); myString.constructor myString.length myString.prototype myString.charAt() myString.charCodeAt() myString.concat() myString.indexOf() myString.lastIndexOf() myString.length() myString.localeCompare() myString.match() myString.replace() myString.search() myString.slice() myString.split() myString.substr() myString.substring() myString.toLocaleLowerCase() myString.toLocaleUpperCase() myString.toLowerCase() myString.toString() myString.toUpperCase() myString.valueOf() |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 | // Arrays var array_name[:datatype]; // Declaration array_name = [val1,val2,valn..] // Initialization var array_name[:data type] = [val1,val2…valn] var nums:number[:int] = [1,2,3,3] // Declare Type var nums:number[] = [1,2,3,3] // Infer Type var arr_names:number[] = new Array(4) var arr_names:number[] = new Array(1, 2, 3, 4) array_name[subscript] // Get array_name[subscript] = value // Set // Destructuring var arr:number[] = [12,13] var[x,y] = arr // For loop Access for(var i = 0;i<arr_names.length;i++) { console.log(arr_names[i]) } for(i in arr_names) { console.log(i) } // Array Functions concat() every() filter() forEach() indexOf() join() lastIndexOf() map() pop() push() reduce() reduceRight() reverse() shift() slice() some() sort() splice() toString() unshift() |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | // Tuples var tuple_name = [value1,value2,value3,…value n] var mytuple = [10,"Hello"]; var mytuple = []; mytuple[0] // Get mytuple[0] = 120 // Set mytuple[1] = 234 // Set // Destructuring var a =[10,"hello"] var [b,c] = a // Methods length() push() pop() |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | // Unions var val:string|number // Can be a number or string at any time val = 12 val = "This is a string" // As a function parameter function disp(name:string|string[]) { if(typeof name == "string") { // do something with a striing } else { // do something with a string array } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | // Interfaces // Interfaces define properties, methods, and events, // which are the members of the interface interface IPerson { firstName:string, lastName:string, sayHi: ()=>string } var customer:IPerson = { firstName:"Tom", lastName:"Hanks", sayHi: ():string =>{return "Hi there"} } // Interface inheritance interface Person { age:number } interface Musician extends Person { instrument:string } // Interface Multiple Inheritiance interface IParent1 { v1:number } interface IParent2 { v2:number } interface Child extends IParent1, IParent2 { } var Iobj:Child = { v1:12, v2:23} |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 | // Classes // Declaring class Car { //field engine:string; //constructor constructor(engine:string) { this.engine = engine } //function disp():void { console.log("Engine is : "+this.engine) } } // Creata an instance var obj = new Car("Engine 1") // Access Fields console.log("Reading attribute value Engine as : "+obj.engine) // Access Functions obj.disp() // 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); // Multiple Inheritance class BaseClass1 {} class BaseClass2 {} class MyClass extends BaseClass1, BaseClass2 {} // Method overriding class BaseClass { public myFunc(val1:number): string { return "Hello" } } class MyClass extends BaseClass{ public myFunc(val1:number): string { return "Hello World" } } // Static Keyword class StaticMem { static num:number; static disp():void { console.log("The value of num is"+ StaticMem.num) } } // Data Hiding class Encapsulate { val1:string = "hello" // Default to public public val2:string = "world" // Defined as public protected val3:number = 42 // Defined as protected private val4:string = "password" // Defined as private } // Interfaces interface ILoan { interest:number } class AgriLoan implements ILoan { interest:number rebate:number constructor(interest:number,rebate:number) { this.interest = interest this.rebate = rebate } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | // Objects var object_name = { key1: “value1”, //scalar value key2: “value”, key3: function() { //functions }, key4:[“content1”, “content2”] //collection }; // Anonymous Objects var invokeperson = function(obj:{ firstname:string, lastname :string}) { console.log("first name :"+obj.firstname) console.log("last name :"+obj.lastname) } invokeperson({firstname:"Sachin",lastname:"Tendulkar"}); |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | // Namespaces FileName :IShape.ts ---------- namespace Drawing { export interface IShape { draw(); } } FileName :Circle.ts ---------- /// <reference path = "IShape.ts" /> namespace Drawing { export class Circle implements IShape { public draw() { console.log("Circle is drawn"); } FileName :Triangle.ts ---------- /// <reference path = "IShape.ts" /> namespace Drawing { export class Triangle implements IShape { public draw() { console.log("Triangle is drawn"); } } FileName : TestShape.ts /// <reference path = "IShape.ts" /> /// <reference path = "Circle.ts" /> /// <reference path = "Triangle.ts" /> function drawAllShapes(shape:Drawing.IShape) { shape.draw(); } drawAllShapes(new Drawing.Circle()); drawAllShapes(new Drawing.Triangle()); } } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | // Modules // External Modules Only // IShape.ts export interface IShape { draw(); } // Circle.ts import shape = require("./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()); |
1 2 3 4 5 6 7 8 9 10 11 12 13 | // Ambients // When include Javascript files/source in your TS project FileName: CalcThirdPartyJsLib.js // Contains 3rd party javascript FileName: Calc.d.ts // Our typescript code FileName : CalcTest.ts // Usiing both js and ts in this file /// <reference path = "Calc.d.ts" /> |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | // Typescript Keywords break as any switch case if throw else var number string get module type instanceof typeof public private enum export finally for while void null super this new in return true false any extends static let package implements interface function new try yield const continue do catch |