TypeScript – Numbers

TypeScript – Numbers ”; Previous Next TypeScript like JavaScript supports numeric values as Number objects. A number object converts numeric literal to an instance of the number class. The Number class acts as a wrapper and enables manipulation of numeric literals as they were objects. TypeScript number type represents the numeric values. All the numbers are represented as the floating point values. TypeScript also supports the binary, octal and hexadecimal numbers introduced in ECMAScript 2015. In TypeScript, we can create a number primitive as well as Number object. Syntax We can declare a variable of number type using colon (:) after the variable name followed by number − let varName: number = value; In the above syntax, we declared a variable named varName of number type. Here value is the any numeric value such as decimal, binary, octal or hexadecimal numbers. We can create the Number object. To create a Number object we can use the Number() constructor as follows − var var_name = new Number(value) In case a non-numeric argument is passed as an argument to the Number’s constructor, it returns NaN (Not–a–Number) The type ”Number” is a wrapper object but type ”number” is a primitive. Prefer using ”number” when possible. Type ”Number” is not assignable to type ”number”. Creating Number Types In the below example, we created a variable count of number type. We assigned 10 to the count. let count: number = 10; console.log(count); On compiling, it will generate the following JavaScript code. let count = 10; console.log(count); The output is as follows − 10 We can also assign float, binary, octal and hexadecimal values to a variable of number type. Look at the below TypeScript code snippet – let decNum: number = 10.6; // floating point number let binNum: number = 0b101001; // binary number let octNum: number = 0o45; // octal number let hexNum: number = 0x80fd; // hexadecimal number Creating Number Object const count = new Number(10); console.log(count); console.log(typeof count); On compiling, it will generate the same JavaScript code. The output of the above example code is as follows – [Number: 10] Object Number Properties The following table lists a set of properties of the Number object − S.No. Property & Description 1. MAX_VALUE The largest possible value a number in JavaScript can have 1.7976931348623157E&plus;308. 2. MIN_VALUE The smallest possible value a number in JavaScript can have 5E-324. 3. NaN Equal to a value that is not a number. 4. NEGATIVE_INFINITY A value that is less than MIN_VALUE. 5. POSITIVE_INFINITY A value that is greater than MAX_VALUE. 6. prototype A static property of the Number object. Use the prototype property to assign new properties and methods to the Number object in the current document. 7. constructor Returns the function that created this object”s instance. By default, this is the Number object. Example console.log(“TypeScript Number Properties: “); console.log(“Maximum value that a number variable can hold: ” + Number.MAX_VALUE); console.log(“The least value that a number variable can hold: ” + Number.MIN_VALUE); console.log(“Value of Negative Infinity: ” + Number.NEGATIVE_INFINITY); console.log(“Value of Negative Infinity:” + Number.POSITIVE_INFINITY); On compiling, it will generate the same code in JavaScript. Its output is as follows − TypeScript Number Properties: Maximum value that a number variable can hold: 1.7976931348623157e+308 The least value that a number variable can hold: 5e-324 Value of Negative Infinity: -Infinity Value of Negative Infinity:Infinity Example: NaN var month = 0 if( month<=0 || month >12) { month = Number.NaN console.log(“Month is “+ month) } else { console.log(“Value Accepted..”) } On compiling, it will generate the same code in JavaScript. Its output is as follows − Month is NaN Example: prototype function employee(id:number,name:string) { this.id = id this.name = name } var emp = new employee(123,”Smith”) employee.prototype.email = “[email protected]” console.log(“Employee”s Id: “+emp.id) console.log(“Employee”s name: “+emp.name) console.log(“Employee”s Email ID: “+emp.email) On compiling, it will generate the following JavaScript code − //Generated by typescript 1.8.10 function employee(id, name) { this.id = id; this.name = name; } var emp = new employee(123, “Smith”); employee.prototype.email = “[email protected]”; console.log(“Employee ”s Id: ” + emp.id); console.log(“Employee”s name: ” + emp.name); console.log(“Employee”s Email ID: ” + emp.email); Its output is as follows − Employee”s Id: 123 Emaployee”s name: Smith Employee”s Email ID: [email protected] Number Methods The Number object contains only the default methods that are a part of every object”s definition. Some of the commonly used methods are listed below − S.No. Methods & Description 1. toExponential() Forces a number to display in exponential notation, even if the number is in the range in which JavaScript normally uses standard notation. 2. toFixed() Formats a number with a specific number of digits to the right of the decimal. 3. toLocaleString() Returns a string value version of the current number in a format that may vary according to a browser”s local settings. 4. toPrecision() Defines how many total digits (including digits to the left and right of the decimal) to display of a number. A negative precision will throw an error. 5. toString() Returns the string representation of the number”s value. The function is passed the radix, an integer between 2 and 36 specifying the base to use for representing numeric values. 6. valueOf() Returns the number”s primitive value. Print Page Previous Next Advertisements ”;

TypeScript – Tuples

TypeScript – Tuples ”; Previous Next At times, there might be a need to store a collection of values of varied types. Arrays will not serve this purpose. TypeScript gives us a data type called tuple that helps to achieve such a purpose. It represents a heterogeneous collection of values. In other words, tuples enable storing multiple fields of different types. Tuples can also be passed as parameters to functions. Syntax We can create a tuple using JavaScript’s array syntax: const tupleName = [value1, value2, value3, …valueN] But we need to declare its type as a tuple. const tupleName: [type1, type2, type3, …typeN] = [value1, value2, value3, …valueN] For Example const myTuple: [number, string] = [10,”Hello”]; You can define a tuple first and then initialize, let myTuple: [number, string]; // declaring the tuple myTuple = [10, “Hello”]; // initializing the tuple Make sure, the const tuple declared must be initialized. You can also declare an empty tuple in Typescript and choose to initialize it later. var myTuple = []; myTuple[0] = 10; myTuple[1] = “Hello”; Accessing Values in Tuples Tuple values are individually called items. Tuples are index based. This means that items in a tuple can be accessed using their corresponding numeric index. Tuple item’s index starts from zero and extends up to n-1(where n is the tuple’s size). Syntax Following is the syntax to access the values in a tuple using its index − tupleName[index] Example: Simple Tuple var myTuple: [number, string] = [10,”Hello”]; //create a tuple console.log(myTuple[0]) console.log(myTuple[1]) In the above example, a tuple, myTuple, is declared. The tuple contains values of numeric and string types respectively. On compiling, it will generate the following code in JavaScript. var myTuple = [10, “Hello”]; //create a tuple console.log(myTuple[0]); console.log(myTuple[1]); Its output is as follows − 10 Hello Example: Empty Tuple We can declare an empty tuple as follows and then initialize it. var tup = [] tup[0] = 12 tup[1] = 23 console.log(tup[0]) console.log(tup[1]) On compiling, it will generate the same code in JavaScript. Its output is as follows − 12 23 Tuple Operations Tuples in TypeScript supports various operations like pushing a new item, removing an item from the tuple, etc. Example var myTuple: [number, string, string, string]; myTuple = [10,”Hello”,”World”,”typeScript”]; console.log(“Items before push ” + myTuple.length) myTuple.push(12) // append value to the tuple console.log(“Items after push ” + myTuple.length) console.log(“Items before pop ” + myTuple.length) // removes and returns the last item console.log(myTuple.pop() + ” popped from the tuple”) console.log(“Items after pop ” + myTuple.length) The push() appends an item to the tuple The pop() removes and returns the last value in the tuple On compiling, it will generate the following code in JavaScript. var myTuple; myTuple = [10, “Hello”, “World”, “typeScript”]; console.log(“Items before push ” + myTuple.length); myTuple.push(12); // append value to the tuple console.log(“Items after push ” + myTuple.length); console.log(“Items before pop ” + myTuple.length); // removes and returns the last item console.log(myTuple.pop() + ” popped from the tuple”); console.log(“Items after pop ” + myTuple.length); The output of the above code is as follows − Items before push 4 Items after push 5 Items before pop 5 12 popped from the tuple Items after pop 4 Updating Tuples Tuples are mutable which means you can update or change the values of tuple elements. Example var myTuple: [number, string, string, string]; // define tuple myTuple = [10,”Hello”,”World”,”typeScript”]; // initialize tuple console.log(“Tuple value at index 0 ” + myTuple[0]) //update a tuple element myTuple[0] = 121 console.log(“Tuple value at index 0 changed to ” + myTuple[0]) On compiling, it will generate the following code in JavaScript. var myTuple; // define tuple myTuple = [10, “Hello”, “World”, “typeScript”]; // initialize tuple console.log(“Tuple value at index 0 ” + myTuple[0]); //update a tuple element myTuple[0] = 121; console.log(“Tuple value at index 0 changed to ” + myTuple[0]); The output of the above code is as follows − Tuple value at index 0 10 Tuple value at index 0 changed to 121 Destructuring a Tuple Destructuring refers to breaking up the structure of an entity. TypeScript supports destructuring when used in the context of a tuple. Example var a: [number, string] = [10,”hello”]; var [b, c] = a; console.log( b ); console.log( c ); On compiling, it will generate following JavaScript code. var a = [10, “hello”]; var b = a[0], c = a[1]; console.log(b); console.log(c); Its output is as follows − 10 hello Function Parameters and Tuple Types We can define a function to accept explicitly a tuple type. So while calling the function we pass the tuple as argument. Example function processData(data: [string, number]): void { const [name, age] = data; console.log(`Name: ${name}, Age: ${age}`); } let data: [string, number] = [“John”, 32] processData(data); We defined here a function processData() that accepts a parameter of tuple type. Inside the function we use tuple destructuring to get the constituent elements. We call the function passing a tuple as argument. On compiling, it will generate the following JavaScript code. function processData(data) { const [name, age] = data; console.log(`Name: ${name}, Age: ${age}`); } let data = [“John”, 32]; processData(data); The output of the above code is as follows − Name: John, Age: 32 Print Page Previous Next Advertisements ”;

TypeScript – Rest Parameter

TypeScript – The Rest Parameter ”; Previous Next The Rest Parameter In TypeScript, a rest parameter allows a function to accept a variable number of arguments and store them as an array. This is useful when you want to define a function that can handle a variable number of arguments. The rest parameter allows you to collect remaining arguments into a single array. The name of the rest parameter becomes the variable that holds this array. Rest Parameter Syntax The rest parameter is written using ellipsis/ three dots (…) followed by a parameter name in the function declaration. We use the array type for the type annotation of the rest parameter. function funcName(…rest: type[]): returnType{ // function body; } Where, funcName − It”s the name of our function. …rest − it stores the multiple arguments to the array named rest. type[] − it specifies the type of the arguments A function can have any number of ordinary parameters along with the rest parameter. A rest parameter must be last in the parameter list. function funcName (…rest1: type[], param1: type){} //Error : A rest parameter must be last in a parameter list. There must be only a single rest parameter in the function definition. function funcName (…rest1: type[], …rest2: number[]){} //Error: A rest parameter must be last in a parameter list. Same as above function declaration, the function expression can also have a rest parameter. let getSum = function(…rest: type[]){ function body; } Examples Let”s understand the rest parameters with help of some examples in TypeScript. Example: Variable Length Parameter List Using the rest parameter, we can call the function with a varying number of arguments. The rest parameter can handle these varying number of arguments. In the example below, we have defined a function named sum with a rest parameter …nums. The arguments are stored as elements of array nums. Each time we call the function with different number of arguments, nums stores the arguments. And we can perform any operation of array on nums. function sum(…nums: number[]) { let totalSum = 0; for (let num of nums) { totalSum += num; } return totalSum; } console.log(sum(10, 20, 30, 40)); console.log(sum(10, 20)); console.log(sum()); On compiling, it will generate the following JavaScript code. function sum(…nums) { let totalSum = 0; for (let num of nums) { totalSum += num; } return totalSum; } console.log(sum(10, 20, 30, 40)); console.log(sum(10, 20)); console.log(sum()); The output of the above example code is as follows − 100 30 0 Example: Accessing argument length In this example, we define a function named getLen with rest parameter …theArgs. We use the length property of array to get the length or number of arguments. function getLen(…theArgs:number[]) { console.log(theArgs.length); } getLen(); getLen(5); getLen(5, 6, 7); On compiling, it will generate the following JavaScript code. function getLen(…theArgs) { console.log(theArgs.length); } getLen(); getLen(5); getLen(5, 6, 7); The output of the above example code is as follows − 0 1 3 Rest Parameter & Spread Operator We have discussed about the rest parameters. The spread operator denoted with three dots (…) same as the rest parameters but works differently. A rest parameter is used to collect the remaining parameters as an array. The spread operator spreads out the elements of an array into individual elements. A spread argument must either have a tuple type or be passed to a rest parameter. Example: Array as spread arguments In this example, we defined two arrays arr1 and arr2 with three elements each. We call push() method on arr1 passing …arr2 as an argument. This works as spread argument as it spreads out/ unpacks the elements of the arr2 into the individual elements. const arr1: number[] = [10, 20, 30]; const arr2: number[] = [40, 50, 60]; arr1.push(…arr2); console.log(arr1); On compiling, it will generate the following JavaScript code. const arr1 = [10, 20, 30]; const arr2 = [40, 50, 60]; arr1.push(…arr2); console.log(arr1); The output of the above code is as follows − [10, 20, 30, 40, 50, 60] Example: Finding max/min number In the example below, we find the maximum number. We define a function named getMax with a parameter, …args: number[]. We call Math.max() method passing argument, …args. The three dots in the argument, …args, works as spread operator. It spreads/ unpacks the elements of the array args. function getMax(…args:number[]){ // here …args as rest parameter return Math.max(…args); // here … works as spread operator } console.log(getMax(10,20,30,40)); console.log(getMax(10,20,30)); On compiling, it will generate the following JavaScript code. function getMax(…args) { return Math.max(…args); // here … works as spread operator } console.log(getMax(10, 20, 30, 40)); console.log(getMax(10, 20, 30)); The output of the above example code is as follows − 40 30 Example: Passing rest argument The rest argument unpacks the argument into the individual elements. In this example, we define a function named multiply that takes three parameters of number types and return their product. The return type of the function is also number. We call the function passing a rest argument (…numbers). function multiply(a: number, b: number, c: number): number { return a * b * c; } let numbers: [number, number, number]; numbers = [2, 3, 4]; console.log(multiply(…numbers)); On compiling, it will generate the following JavaScript code. function multiply(a, b, c) { return a * b * c; } let numbers; numbers = [2, 3, 4]; console.log(multiply(…numbers)); The output of the above example code is as follows − 24 Print Page Previous Next Advertisements ”;

TypeScript – Basic Syntax

TypeScript – Basic Syntax ”; Previous Next Syntax defines a set of rules for writing programs. Every language specification defines its own syntax. A TypeScript program is composed of − Modules Functions Variables Statements and Expressions Comments Your First TypeScript Code Let us start with the traditional “Hello World” example − var message:string = “Hello World” console.log(message) On compiling, it will generate following JavaScript code. var message = “Hello World”; console.log(message); Line 1 declares a variable by the name message. Variables are a mechanism to store values in a program. Line 2 prints the variable’s value to the prompt. Here, console refers to the terminal window. The function log () is used to display text on the screen. Compile and Execute a TypeScript Program Let us see how to compile and execute a TypeScript program using Visual Studio Code. Follow the steps given below − Step 1 − Save the file with .ts extension. We shall save the file as Test.ts. The code editor marks errors in the code, if any, while you save it. Step 2 − Right-click the TypeScript file under the Working Files option in VS Code’s Explore Pane. Select Open in Command Prompt option. Step 3 − To compile the file use the following command on the terminal window. tsc Test.ts Step 4 − The file is compiled to Test.js. To run the program written, type the following in the terminal. node Test.js Compiler Flags Compiler flags enable you to change the behavior of the compiler during compilation. Each compiler flag exposes a setting that allows you to change how the compiler behaves. The following table lists some common flags associated with the TSC compiler. A typical command-line usage uses some or all switches. S.No. Compiler flag & Description 1. –help Displays the help manual 2. –module Load external modules 3. –target Set the target ECMA version 4. –declaration Generates an additional .d.ts file 5. –removeComments Removes all comments from the output file 6. –out Compile multiple files into a single output file 7. –sourcemap Generate a sourcemap (.map) files 8. –module noImplicitAny Disallows the compiler from inferring the any type 9. –watch Watch for file changes and recompile them on the fly Note − Multiple files can be compiled at once. tsc file1.ts, file2.ts, file3.ts Identifiers in TypeScript Identifiers are names given to elements in a program like variables, functions etc. The rules for identifiers are − Identifiers can include both, characters and digits. However, the identifier cannot begin with a digit. Identifiers cannot include special symbols except for underscore (_) or a dollar sign (&dollar;). Identifiers cannot be keywords. They must be unique. Identifiers are case-sensitive. Identifiers cannot contain spaces. The following tables lists a few examples of valid and invalid identifiers − Valid identifiers Invalid identifiers firstName Var first_name first name num1 first-name &dollar;result 1number TypeScript ─ Keywords Keywords have a special meaning in the context of a language. The following table lists some keywords in TypeScript. 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 Whitespace and Line Breaks TypeScript ignores spaces, tabs, and newlines that appear in programs. You can use spaces, tabs, and newlines freely in your program and you are free to format and indent your programs in a neat and consistent way that makes the code easy to read and understand. TypeScript is Case-sensitive TypeScript is case-sensitive. This means that TypeScript differentiates between uppercase and lowercase characters. Semicolons are optional Each line of instruction is called a statement. Semicolons are optional in TypeScript. Example console.log(“hello world”) console.log(“We are learning TypeScript”) A single line can contain multiple statements. However, these statements must be separated by a semicolon. Comments in TypeScript Comments are a way to improve the readability of a program. Comments can be used to include additional information about a program like author of the code, hints about a function/ construct etc. Comments are ignored by the compiler. TypeScript supports the following types of comments − Single-line comments ( // ) − Any text between a // and the end of a line is treated as a comment Multi-line comments (/* */) − These comments may span multiple lines. Example //this is single line comment /* This is a Multi-line comment */ TypeScript and Object Orientation TypeScript is Object-Oriented JavaScript. Object Orientation is a software development paradigm that follows real-world modelling. Object Orientation considers a program as a collection of objects that communicate with each other via mechanism called methods. TypeScript supports these object oriented components too. Object − An object is a real time representation of any entity. According to Grady Brooch, every object must have three features − State − described by the attributes of an object Behavior − describes how the object will act Identity − a unique value that distinguishes an object from a set of similar such objects. Class − A class in terms of OOP is a blueprint for creating objects. A class encapsulates data for the object. Method − Methods facilitate communication between objects. Example: TypeScript and Object Orientation class Greeting { greet():void { console.log(“Hello World!!!”) } } var obj = new Greeting(); obj.greet(); The above example defines a class Greeting. The class has a method greet (). The method prints the string “Hello World” on the terminal. The new keyword creates an object of the class (obj). The object invokes the method greet (). On compiling, it will generate following JavaScript code. var Greeting = (function () { function Greeting() { } Greeting.prototype.greet = function () { console.log(“Hello World!!!”); }; return Greeting; }()); var obj = new Greeting(); obj.greet() The output of the above program is given below − Hello World!!! Print Page Previous Next

TypeScript – Features

TypeScript – Features ”; Previous Next TypeScript is a superset of JavaScript. So, it contains all the features that JavaScript has. However, it also contains some advanced features that JavaScript doesn”t have like static typing, interface, etc. Let”s discuss some of the important features of TypeScript. Type Annotation In TypeScript, type annotation allows you to declare the type of variable, function parameters, and return value. The static typing feature of TypeScript allows you to catch type-related errors while writing the code instead of at the compile time. This way developers can write more reliable code. Example In the code below, we have defined the variable ”a” of the number data type. The printNumber() function takes the ”num” parameter of the ”number” type. The function prints the parameter value. // Type annotation in TypeScript var a: number = 10; function printNumber(num: number) { console.log(num); } printNumber(a); On compiling, it will generate the following JavaScript code. // Type annotation in TypeScript var a = 10; function printNumber(num) { console.log(num); } printNumber(a); Output The above example code will produce the following output – 10 Interfaces Interfaces are similar to the abstract classes in other programming languages like Java. It allows developers to define the structure of the object but doesn”t provide the implementation. This way developers can adhere to the same structure of the object for similar kinds of objects. Example In the example below, we have defined the ”Iperson” interface that contains the ”firstName”, and ”lastName” properties and getFullName() method. The interface declares the properties and methods only, defining the structure of the object. For the ”obj” object, we have used the ”IPerson” interface as a type. After that, we initialized the properties of an object and implemented the getFullName() method which returns the string value. // Interfaces in TypeScript interface IPerson { firstName: string; lastName: string; getFullName(): string; } // Define an object that implements the interface let obj: IPerson = { firstName: “John”, lastName: “Doe”, getFullName(): string { return this.firstName + ” ” + this.lastName; } }; console.log(obj.getFullName()); On compiling, it will generate the following JavaScript code. // Define an object that implements the interface let obj = { firstName: “John”, lastName: “Doe”, getFullName() { return this.firstName + ” ” + this.lastName; } }; console.log(obj.getFullName()); Output The output of the above example code is as follows – John Doe Classes Classes are a blueprint of the objects. Classes can contain properties, and methods which can be accessed using an instance of classes. You can use class constructor() to initialize the properties of the class while creating the instance of the class. Furthermore, you can also have static members inside the classes which can be accessed through the class name and without using an instance of the class. Example In the code below, we have created the Greeter class, which contains the ”greeting” property. The constructor() method takes the ”message” parameter and initializes the ”greeting” property values with it. The greet() method returns the string value, representing the greeting message. After that, we have created the instance of the Greeter class and called the greet() method using it. // Basic example of class class Greeter { greeting: string; // Constructor method constructor(message: string) { this.greeting = message; } // Class Method greet() { return “Hello, ” + this.greeting; } } // Create an instance of the class let greeter = new Greeter(“world”); console.log(greeter.greet()); // Hello, world On compiling, it will generate the following JavaScript code. // Basic example of class class Greeter { // Constructor method constructor(message) { this.greeting = message; } // Class Method greet() { return “Hello, ” + this.greeting; } } // Create an instance of the class let greeter = new Greeter(“world”); console.log(greeter.greet()); // Hello, world Output The output of the above example code is as follows – Hello, world Inheritance TypeScript supports all features of the object-oriented programming language like polymorphism, abstraction, encapsulation, inheritance etc. However, we have covered inheritance only in this lesson. Inheritance allows you to reuse the properties and methods of other classes. Example In the code below, the ”Person” class is a base class. It contains the ”name” property, which we initialize in the constructor() method. The display() method prints the name in the console. The Employee class inherits the properties of the Parent class using the ”extends” keyword. It contains the ”empCode” property and show() method. It also contains all properties and methods of the Person class. Next, we created the instance of the Employee class and accessed the method of the Person class using it. // Base class class Person { name: string; constructor(name: string) { this.name = name; } display(): void { console.log(this.name); } } // Derived class class Employee extends Person { empCode: number; constructor(name: string, code: number) { super(name); this.empCode = code; } show(): void { console.log(this.empCode); } } let emp: Employee = new Employee(“John”, 123); emp.display(); // John emp.show(); // 123 On compiling, it will produce the following JavaScript code. // Base class class Person { constructor(name) { this.name = name; } display() { console.log(this.name); } } // Derived class class Employee extends Person { constructor(name, code) { super(name); this.empCode = code; } show() { console.log(this.empCode); } } let emp = new Employee(“John”, 123); emp.display(); // John emp.show(); // 123 Output The output of the above example code is as follows – John 123 Enums Enums are used to define the named constants in TypeScript. It allows you to give names to the constant values, which makes code more reliable and readable. Example In the code below, we have used the ”enum” keyword to define the enum. In our case, the integer value represents the directions, but we have given names to the directions for better readability. After that, you can use the constant name to access the value of the Directions. // Enums in TypeScript enum Direction { Up = 1, Down, Left, Right } console.log(Direction.Up); // 1 console.log(Direction.Down); // 2 console.log(Direction.Left); // 3 console.log(Direction.Right); // 4 On compiling, it will

TypeScript – Arrays

TypeScript – Arrays ”; Previous Next The use of variables to store values poses the following limitations − Variables are scalar in nature. In other words, a variable declaration can only contain a single at a time. This means that to store n values in a program n variable declarations will be needed. Hence, the use of variables is not feasible when one needs to store a larger collection of values. Variables in a program are allocated memory in random order, thereby making it difficult to retrieve/read the values in the order of their declaration. TypeScript introduces the concept of arrays to tackle the same. An array is a homogenous collection of values. To simplify, an array is a collection of values of the same data type. It is a user defined type. Features of an Array Here is a list of the features of an array − An array declaration allocates sequential memory blocks. Arrays are static. This means that an array once initialized cannot be resized. Each memory block represents an array element. Array elements are identified by a unique integer called as the subscript / index of the element. Like variables, arrays too, should be declared before they are used. Use the var keyword to declare an array. Array initialization refers to populating the array elements. Array element values can be updated or modified but cannot be deleted. Declaring and Initializing Arrays To declare an initialize an array in Typescript use the following syntax − Syntax var array_name[:datatype]; //declaration array_name = [val1,val2,valn..] //initialization An array declaration without the data type is deemed to be of the type any. The type of such an array is inferred from the data type of the array’s first element during initialization. For example, a declaration like − var numlist:number[] = [2,4,6,8] will create an array as given below − The array pointer refers to the first element by default. Arrays may be declared and initialized in a single statement. The syntax for the same is − var array_name[:data type] = [val1,val2…valn] Note − The pair of [] is called the dimension of the array. Accessing Array Elements The array name followed by the subscript is used refer to an array element. Its syntax is as follows − array_name[subscript] = value Example: Simple Array var alphas:string[]; alphas = [“1″,”2″,”3″,”4”] console.log(alphas[0]); console.log(alphas[1]); On compiling, it will generate following JavaScript code − var alphas; alphas = [“1”, “2”, “3”, “4”]; console.log(alphas[0]); console.log(alphas[1]); The output of the above code is as follows − 1 2 Example: Single statement declaration and initialization var nums:number[] = [1,2,3,3] console.log(nums[0]); console.log(nums[1]); console.log(nums[2]); console.log(nums[3]); On compiling, it will generate following JavaScript code − var nums = [1, 2, 3, 3]; console.log(nums[0]); console.log(nums[1]); console.log(nums[2]); console.log(nums[3]); Its output is as follows − 1 2 3 3 Array Object An array can also be created using the Array object. The Array constructor can be passed. A numeric value that represents the size of the array or A list of comma separated values. The following example shows how to create an array using this method. Example var arr_names:number[] = new Array(4) for(var i = 0;i<arr_names.length;i++) { arr_names[i] = i * 2 console.log(arr_names[i]) } On compiling, it will generate following JavaScript code. var arr_names = new Array(4); for (var i = 0; i < arr_names.length; i++) { arr_names[i] = i * 2; console.log(arr_names[i]); } Its output is as follows − 0 2 4 6 Example: Array Constructor accepts comma separated values var names:string[] = new Array(“Mary”,”Tom”,”Jack”,”Jill”) for(var i = 0;i<names.length;i++) { console.log(names[i]) } On compiling, it will generate following JavaScript code − var names = new Array(“Mary”, “Tom”, “Jack”, “Jill”); for (var i = 0; i < names.length; i++) { console.log(names[i]); } Its output is as follows − Mary Tom Jack Jill Array Methods A list of the methods of the Array object along with their description is given below. S.No. Method & Description 1. concat() Returns a new array comprised of this array joined with other array(s) and/or value(s). 2. every() Returns true if every element in this array satisfies the provided testing function. 3. filter() Creates a new array with all of the elements of this array for which the provided filtering function returns true. 4. forEach() Calls a function for each element in the array. 5. indexOf() Returns the first (least) index of an element within the array equal to the specified value, or -1 if none is found. 6. join() Joins all elements of an array into a string. 7. lastIndexOf() Returns the last (greatest) index of an element within the array equal to the specified value, or -1 if none is found. 8. map() Creates a new array with the results of calling a provided function on every element in this array. 9. pop() Removes the last element from an array and returns that element. 10. push() Adds one or more elements to the end of an array and returns the new length of the array. 11. reduce() Apply a function simultaneously against two values of the array (from left-to-right) as to reduce it to a single value. 12. reduceRight() Apply a function simultaneously against two values of the array (from right-to-left) as to reduce it to a single value. 13. reverse() Reverses the order of the elements of an array — the first becomes the last, and the last becomes the first. 14. shift() Removes the first element from an array and returns that element. 15. slice() Extracts a section of an array and returns a new array. 16. some() Returns true if at least one element in this array satisfies the provided testing function. 17. sort() Sorts the elements of an array. 18. splice() Adds and/or removes elements from an array. 19. toString() Returns a string representing the array and its elements. 20. unshift() Adds one or more elements to the front of an array and returns the new length of the array. Array Destructuring Refers to breaking up the structure of an entity.

TypeScript – Environment Setup

TypeScript – Environment Setup ”; Previous Next We already have set up TypeScript programming online, so that you can execute all the available examples online at the same time when you are doing your theory work. This gives you confidence in what you are reading and to check the result with different options. Feel free to modify any example and execute it online. var message:string = “Hello World” console.log(message) On compiling, it will generate following JavaScript code. var message = “Hello World”; console.log(message); In this chapter, we will discuss how to install TypeScript on Windows platform. We will also explain how to install the Brackets IDE. You may test your scripts online by using The TypeScript at www.typescriptlang.org/Playground. The online editor shows the corresponding JavaScript emitted by the compiler. You may try the following example using Playground. var num:number = 12 console.log(num) On compiling , it will generate following JavaScript code. var num = 12; console.log(num); The output of the above program is given below − 12 Local Environment Setup Typescript is an Open Source technology. It can run on any browser, any host, and any OS. You will need the following tools to write and test a Typescript program − A Text Editor The text editor helps you to write your source code. Examples of a few editors include Windows Notepad, Notepad&plus;&plus;, Emacs, vim or vi, etc. Editors used may vary with Operating Systems. The source files are typically named with the extension .ts The TypeScript Compiler The TypeScript compiler is itself a .ts file compiled down to JavaScript (.js) file. The TSC (TypeScript Compiler) is a source-to-source compiler (transcompiler / transpiler). The TSC generates a JavaScript version of the .ts file passed to it. In other words, the TSC produces an equivalent JavaScript source code from the Typescript file given as an input to it. This process is termed as transpilation. However, the compiler rejects any raw JavaScript file passed to it. The compiler deals with only .ts or .d.ts files. This TypeScript tutorial is based on the latest typescript 5.5.2 version. Installing Node.js Node.js is an open source, cross-platform runtime environment for server-side JavaScript. Node.js is required to run JavaScript without a browser support. It uses Google V8 JavaScript engine to execute code. You may download Node.js source code or a pre-built installer for your platform. Node is available here − https://nodejs.org/en/download Installation on Windows Follow the steps given below to install Node.js in Windows environment. Step 1 − Download and run the .msi installer for Node. Step 2 − To verify if the installation was successful, enter the command node –v in the terminal window. Step 3 − Type the following command in the terminal window to install TypeScript. npm install -g typescript Installation on Mac OS X To install node.js on Mac OS X, you can download a pre-compiled binary package which makes a nice and easy installation. Head over to http://nodejs.org/ and click the install button to download the latest package. Install the package from the .dmg by following the install wizard which will install both node and npm. npm is Node Package Manager which facilitates installation of additional packages for node.js. Installation on Linux You need to install a number of dependencies before you can install Node.js and NPM. Ruby and GCC. You’ll need Ruby 1.8.6 or newer and GCC 4.2 or newer. Homebrew. Homebrew is a package manager originally designed for Mac, but it’s been ported to Linux as Linuxbrew. You can learn more about Homebrew at http://brew.sh/ and Linuxbrew at http://brew.sh/linuxbrew Once these dependencies are installed, you may install Node.js by using the following command on the terminal − brew install node. IDE Support Typescript can be built on a plethora of development environments like Visual Studio, Sublime Text 2, WebStorm/PHPStorm, Eclipse, Brackets, etc. Visual Studio Code and Brackets IDEs are discussed here. The development environment used here is Visual Studio Code (Windows platform). Visual Studio Code This is an open source IDE from Visual Studio. It is available for Mac OS X, Linux and Windows platforms. VScode is available at − https://code.visualstudio.com/ Installation on Windows Step 1 − Download Visual Studio Code for Windows. Step 2 − Double-click on VSCodeSetup.exe to launch the setup process. This will only take a minute. Step 3 − A screenshot of the IDE is given below. Step 4 − You may directly traverse to the file’s path by right clicking on the file → open in command prompt. Similarly, the Reveal in Explorer option shows the file in the File Explorer. Installation on Mac OS X Visual Studio Code’s Mac OS X specific installation guide can be found at https://code.visualstudio.com/Docs/editor/setup Installation on Linux Linux specific installation guide for Visual Studio Code can be found at https://code.visualstudio.com/Docs/editor/setup Brackets Brackets is a free open-source editor for web development, created by Adobe Systems. It is available for Linux, Windows and Mac OS X. Brackets is available at http://brackets.io/ TypeScript Extensions for Brackets Brackets supports extensions for adding extra functionality via the Extension Manager. The following steps explain installing TypeScript extensions using the same. Post installation, click on the extension manager icon on the right-hand side of the editor. Enter typescript in the search box. Install the Brackets TSLint and Brackets TypeScript plugins. You can run DOS prompt / shell within Brackets itself by adding one more extension Brackets Shell. Upon installation, you will find an icon of shell on the right-hand side of the editor . Once you click on the icon, you will see the shell window as shown below − Note − Typescript is also available as a plugin for Visual Studio 2012 and 2013 environments (https://www.typescriptlang.org/#Download).VS 2015 and above includes Typescript plugin by default. Now, you are all set!!! Print Page Previous Next Advertisements ”;

TypeScript – Switch Statement

TypeScript – Switch…case Statement ”; Previous Next In TypeScript, the switch statement evaluates an expression, matches the expression’s value to a case clause, and executes statements associated with that case. You can use multiple if…else statements to achieve the similar functionality. However, it is not the best way especially when the all branches depend on a single value. Syntax The syntax of switch case in TypeScript is as follows − switch(variable_expression) { case constant_expr1: { //statements; break; } case constant_expr2: { //statements; break; } default: { //statements; break; } } The value of the variable_expression is tested against all cases in the switch. If the variable matches one of the cases, the corresponding code block is executed. If no case expression matches the matches the value of the variable_expression, the code within the default block is associated. The following rules apply to a switch statement − There can be any number of case statements within a switch. The case statements can include only constants. It cannot be a variable or an expression. The data type of the variable_expression and the constant expression must match. Unless you put a break after each block of code, execution flows into the next block. The case expression must be unique. The default block is optional. Flowchart The following flow chart explains how a switch-case statement works. Example: switch…case 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; } } The example verifies the value of the variable grade against the set of constants (A, B, C, D, and E) and executes the corresponding blocks. If the value in the variable doesn’t match any of the constants mentioned above, the default block will be executed. On compiling, it will generate the following JavaScript code − var grade = “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; } } The above code will produce the following output − Excellent Example: Without break statement When you don’t use the break statement with any case in switch statement, the continue executing the next case without terminating it. In the example below, we haven”t used the break statement with any case. It executes all the cases and print the respective values. var grade: string = ”A”; console.log(“Entering switch block”); switch(grade) { case “A”: { console.log(“Excellent”); } case “B”: { console.log(“Good”); } case “C”: { console.log(“Fair”); } case “D”: { console.log(“Poor”); } default: { console.log(“Invalid choice”); } } console.log(“Exiting switch block”); On compiling, it will generate the following JavaScript code. var grade = ”A”; console.log(“Entering switch block”); switch (grade) { case “A”: { console.log(“Excellent”); } case “B”: { console.log(“Good”); } case “C”: { console.log(“Fair”); } case “D”: { console.log(“Poor”); } default: { console.log(“Invalid choice”); } } console.log(“Exiting switch block”); The output of the above example code is as follows – Entering switch block Excellent Good Fair Poor Invalid choice Exiting switch block Print Page Previous Next Advertisements ”;

TypeScript – Variables

TypeScript – Variables ”; Previous Next A variable, by definition, is “a named space in the memory” that stores values. In other words, it acts as a container for values in a program. TypeScript variables must follow the JavaScript naming rules − Variable names can contain alphabets and numeric digits. They cannot contain spaces and special characters, except the underscore (_) and the dollar (&dollar;) sign. Variable names cannot begin with a digit. A variable must be declared before it is used. Use the var keyword to declare variables. Variable Declaration in TypeScript The type syntax for declaring a variable in TypeScript is to include a colon (:) after the variable name, followed by its type. Just as in JavaScript, we use the var keyword to declare a variable. When you declare a variable, you have four options − Declare its type and value in one statement. Declare its type but no value. In this case, the variable will be set to undefined. Declare its value but no type. The variable type will be set to the data type of the assigned value. Declare neither value not type. In this case, the data type of the variable will be any and will be initialized to undefined. The following table illustrates the valid syntax for variable declaration as discussed above − S.No. Variable Declaration Syntax & Description 1. var name:string = ”mary” The variable stores a value of type string 2. var name:string; The variable is a string variable. The variable’s value is set to undefined by default 3. var name = ”mary” The variable’s type is inferred from the data type of the value. Here, the variable is of the type string 4. var name; The variable’s data type is any. Its value is set to undefined by default. Example: Variables in TypeScript var name:string = “John”; var score1:number = 50; var score2:number = 42.50 var sum = score1 + score2 console.log(“name”+name) console.log(“first score: “+score1) console.log(“second score: “+score2) console.log(“sum of the scores: “+sum) On compiling, it will generate following JavaScript code. //Generated by typescript 1.8.10 var name = “John”; var score1 = 50; var score2 = 42.50; var sum = score1 + score2; console.log(“name” + name); console.log(“first score: ” + score1); console.log(“second score : ” + score2); console.log(“sum of the scores: ” + sum); The output of the above program is given below − name:John first score:50 second score:42.50 sum of the scores:92.50 The TypeScript compiler will generate errors, if we attempt to assign a value to a variable that is not of the same type. Hence, TypeScript follows Strong Typing. The Strong typing syntax ensures that the types specified on either side of the assignment operator (=) are the same. This is why the following code will result in a compilation error − var num:number = “hello” // will result in a compilation error Type Assertion in TypeScript TypeScript allows changing a variable from one type to another. TypeScript refers to this process as Type Assertion. The syntax is to put the target type between < > symbols and place it in front of the variable or expression. The following example explains this concept − Example var str = ”1” var str2:number = <number> <any> str //str is now of type number console.log(typeof(str2)) If you hover the mouse pointer over the type assertion statement in Visual Studio Code, it displays the change in the variable’s data type. Basically it allows the assertion from type S to T succeed if either S is a subtype of T or T is a subtype of S. The reason why it”s not called “type casting” is that casting generally implies some sort of runtime support while, “type assertions” are purely a compile time construct and a way for you to provide hints to the compiler on how you want your code to be analyzed. On compiling, it will generate following JavaScript code. “use strict”; var str = ”1”; var str2 = str; //str is now of type number console.log(typeof (str2)); It will produce the following output − string Inferred Typing in TypeScript Given the fact that, Typescript is strongly typed, this feature is optional. TypeScript also encourages dynamic typing of variables. This means that, TypeScript encourages declaring a variable without a type. In such cases, the compiler will determine the type of the variable on the basis of the value assigned to it. TypeScript will find the first usage of the variable within the code, determine the type to which it has been initially set and then assume the same type for this variable in the rest of your code block. The same is explained in the following code snippet − Example: Inferred Typing var num = 2; // data type inferred as number console.log(“value of num “+num); num = “12”; console.log(num); In the above code snippet − The code declares a variable and sets its value to 2. Note that the variable declaration doesn’t specify the data type. Hence, the program uses inferred typing to determine the data type of the variable, i.e., it assigns the type of the first value that the variable is set to. In this case, num is set to the type number. When the code tries to set the variable’s value to string. The compiler throws an error as the variable’s type is already set to number. It will produce the following output − error TS2011: Cannot convert ”string” to ”number”. TypeScript Variable Scope The scope of a variable specifies where the variable is defined. The availability of a variable within a program is determined by its scope. TypeScript variables can be of the following scopes − Global Scope − Global variables are declared outside the programming constructs. These variables can be accessed from anywhere within your code. Class Scope − These variables are also called fields. Fields or class variables are declared within the class but outside the methods. These variables can be accessed using the object of the class. Fields can

TypeScript – Enums

TypeScript – Enums ”; Previous Next Enums in TypeScript allow you to define a set of named constants. An enum is a way of giving more friendly names to sets of numeric values. Each enum member has a value associated with it. The value can be either constant or computed. The member value can be a numeric or string value. The Enum type in TypeScript is a user-defined data type. TypeScript has some features that are not the type-level extension of the JavaScript. Enum is one of the such few features along with type guards or union. enum enumName { // Enum members } The enums in TypeScript can be categorized in the following three types – Numeric enums String enums Heterogeneous enums Numeric Enums In this type of enum, members of an enum are assigned numeric values. Numeric enums possess an auto-increment nature. For instance, if we assign the number 5 to the first constant variable of the enum, then the following constant variables assign with values incremented by one, like 6 to the second member of the enum, 7 to the next, and so on. Example 1: Default numeric enums By default, enums in TypeScript are numeric. The first member is assigned a value of 0, and subsequent members are incremented by 1. enum Weekday { Monday, Tuesday, Wednesday, Thursday, Friday, } console.log(Weekday.Monday); console.log(Weekday.Tuesday); console.log(Weekday.Wednesday); console.log(Weekday.Thursday); console.log(Weekday.Friday); On compiling, it will generate the following JavaScript code – var Weekday; (function (Weekday) { Weekday[Weekday[“Monday”] = 0] = “Monday”; Weekday[Weekday[“Tuesday”] = 1] = “Tuesday”; Weekday[Weekday[“Wednesday”] = 2] = “Wednesday”; Weekday[Weekday[“Thursday”] = 3] = “Thursday”; Weekday[Weekday[“Friday”] = 4] = “Friday”; })(Weekday || (Weekday = {})); console.log(Weekday.Monday); console.log(Weekday.Tuesday); console.log(Weekday.Wednesday); console.log(Weekday.Thursday); console.log(Weekday.Friday); The output of the above example code is as follows – 0 1 2 3 4 Notice that the first member is initialized with 0 and the subsequent members are incremented by the 1. Example 2: Initiated numeric enums In the below example, we have created an enum type named Color. Inside Color, three const variables are created with names Red, Yellow, and Green. We have initialized the first member and left other members for auto increment. enum Color{ Red = 10, Yellow, Green, } //print const variables values console.log(Color.Red); console.log(Color.Yellow); console.log(Color.Green); On compiling, it will generate the following JavaScript code – var Color; (function (Color) { Color[Color[“Red”] = 10] = “Red”; Color[Color[“Yellow”] = 11] = “Yellow”; Color[Color[“Green”] = 12] = “Green”; })(Color || (Color = {})); //print const variables values console.log(Color.Red); console.log(Color.Yellow); console.log(Color.Green); The output of the above example code is as follows – 10 11 12 Example 3: Fully initialized numeric enums We can also set the values of all members of an enum. In the example below, we have initialized all member of the enum HttpStatus. enum HttpStatus { Success = 200, NotFound = 404, InternalServerError = 500, } console.log(HttpStatus.Success); console.log(HttpStatus.NotFound); console.log(HttpStatus.InternalServerError); On compiling, it will generate the following JavaScript code – var HttpStatus; (function (HttpStatus) { HttpStatus[HttpStatus[“Success”] = 200] = “Success”; HttpStatus[HttpStatus[“NotFound”] = 404] = “NotFound”; HttpStatus[HttpStatus[“InternalServerError”] = 500] = “InternalServerError”; })(HttpStatus || (HttpStatus = {})); console.log(HttpStatus.Success); console.log(HttpStatus.NotFound); console.log(HttpStatus.InternalServerError); The output of the above example code is as follows – 200 404 500 String Enums String enums are similar to numeric ones except that values of enums members are assigned with strings instead of numeric ones. The string enums do not possess auto-increment behavior. Example The following example creates an enum TrafficLight with three members. The members are initialized with string literals. enum TrafficLight { Red = “stop”, Yellow = “caution”, Green = “go”, } console.log(TrafficLight.Red); console.log(TrafficLight.Yellow); console.log(TrafficLight.Green); On compiling, it will generate the following JavaScript code – var TrafficLight; (function (TrafficLight) { TrafficLight[“Red”] = “stop”; TrafficLight[“Yellow”] = “caution”; TrafficLight[“Green”] = “go”; })(TrafficLight || (TrafficLight = {})); console.log(TrafficLight.Red); console.log(TrafficLight.Yellow); console.log(TrafficLight.Green); The output of the above example code is as follows – stop caution go Heterogeneous Enums This is a combination of both numeric and string enums. That is, in this type of enum, we can assign both string values or numeric values to its members. Example In the below example, we have created an enum type of Student. Inside the student are three const variables: Name, Gender, and Mobile. Name and Gender are of literal string types, whereas Mobile is of numeric value. enum student{ Name = “srujana”, Gender = “female”, Mobile = 901234567, } console.log(student.Name); console.log(student.Gender); console.log(student.Mobile); On compiling, it will generate the following JavaScript code – var student; (function (student) { student[“Name”] = “Srujana”; student[“Gender”] = “Female”; student[student[“Mobile”] = 901234567] = “Mobile”; })(student || (student = {})); console.log(student.Name); console.log(student.Gender); console.log(student.Mobile); The output of the above example code is as follows – Srujana Female 901234567 Enums at runtime The enums are real objects that exist at run time. In the below example, the enum E is passed as parameter object to a function. It works, since ”E” has a property named ”y” which is a number. enum En { x, y, z, } function func(obj: { y: number }) { return obj.y; } console.log(func(En)); console.log(typeof En); On compiling, it will generate the following JavaScript code. var En; (function (En) { En[En[“x”] = 0] = “x”; En[En[“y”] = 1] = “y”; En[En[“z”] = 2] = “z”; })(En || (En = {})); function func(obj) { return obj.y; } console.log(func(En)); console.log(typeof En); The output of the above code is as follows – 1 object Enums at compile time When TypeScript enums are compiled, they are converted to JavaScript objects. The object will have a property for each enum member, and the value of each property will be the enum member”s value. The numeric and string enum members behave differently at the compilation. The numeric members are mapped bi-directionally to its corresponding JavaScript object property while string members are mapped uni-directionally to its runtime object property. enum Enum { Name = ”John Doe”, Age = 32, } The above TypeScript code will be compiled to the following JavaScript code – var Enum; (function (Enum) { Enum[“Name”] = “John Doe”; Enum[Enum[“Age”] = 32] = “Age”; })(Enum ||