TypeScript – Default Parameters

TypeScript – Default Parameters ”; Previous Next Default Parameters In TypeScript, we can assign the function parameters some values by default. Such parameters can be explicitly passed values. These parameters are known as default parameters. When a function is called with missing arguments, or argument with undefined values, the function uses these default initialized values. Syntax The syntax of the default parameters in TypeScript is as follows – function functionName(param1[:type], param2[:type] = defaultValue) Here the function functionName() takes two parameters – param1 and param2. The first parameter param1 is required parameter whereas the second parameter param2 is a default parameter. The param2 is initialized with a default value, defaultValue. When the function functionName() is called without passing the value for param2, the defaultValue is used as the value of param2. Let’s understand the function default parameters with the help of some TypeScript example programs. Example: Simple Default Parameters let”s look at the following example, function greet(name: string, age: number = 30){ console.log(`Hi ${name}, your age is ${age}.`) } greet(”John”, 50); greet(”John”); In the example above, the parameter age is a default parameter that is initialized with default value of 30. The parameter name is a required parameter. On compiling, it will generate the following JavaScript code. function greet(name, age = 30) { console.log(`Hi ${name}, your age is ${age}.`); } greet(”John”, 50); greet(”John”); Output Hi John, your age is 50. Hi John, your age is 30. Example: Default parameters after required parameters Default Parameters should come after Required Parameters in the function definition In the following example, we put the default parameter y after the required parameter x. function sum(x: number, y: number=10): number{ return x + y; } console.log(sum (20,30)); console.log(sum (30)); On compiling, it will generate the following JavaScript code. function sum(x, y = 10) { return x + y; } console.log(sum(20, 30)); console.log(sum(30)); The output is as follows – 50 40 Example: Default parameters before required parameters But if you put the default parameter before the required parameter, and call the function without the passing value for default argument it will show an error. Let”s look at the following example – function sum(x: number=10, y:number):number{ return x + y; } console.log(sum(20,30)); // 50 console.log(sum(30)); // NaN The above TypeScript program will show the following error – Expected 2 arguments, but got 1. And produce the following output – 50 NaN Example: Passing a function as a value for default parameter In the example below, we initialized the parameter b with getNum() function as default value. The getNum() function return the number 10. When the second argument is missing, the value returned by the function getNum() is used as the value for the parameter inside the function. function getNum(): number { return 10; } function mul(a: number, b = getNum()) { return a * b; } console.log(mul(20, 5)); console.log(mul(20)) Output 100 200 Optional Parameter vs. Default Parameter We can call a function without passing a value for the default parameter. We can also call a function without passing a value for optional parameter. Example: Default Parameter In the example below, the age parameter has default value as 30. Which means if you are not passing a value for the age parameter, the function will use the default value of 30 for age. function greet(name: string, age: number = 30){ console.log(`Hi ${name}, your age is ${age}.`); } greet(”John”, 50); greet(”John”); On compiling, it will generate the following JavaScript code. function greet(name, age = 30) { console.log(`Hi ${name}, your age is ${age}.`); } greet(”John”, 50); greet(”John”); The output of the above example code is as follows – Hi John, your age is 50. Hi John, your age is 30. Example: Optional Parameter In the below example, the age parameter is optional. This means you can call the greet function without passing a value for age parameter. When called without a value of age parameter. function greet(name: string, age?:number){ if (age) { console.log(`Hello ${name}, you are ${age} years old`); } else{ console.log(`Hello ${name}`); } } greet (”Shahid”, 35); greet (”Shahid”); On compiling, it will generate the following JavaScript. function greet(name, age) { if (age) { console.log(`Hello ${name}, you are ${age} years old`); } else { console.log(`Hello ${name}`); } } greet(”Shahid”, 35); greet(”Shahid”); The output of the above code is as follows – Hello Shahid, you are 35 years old Hello Shahid We can”t declare a parameter optional and default at the same time. function greet(name: string, age?: number = 30){ console.log(`Hi ${name}, your age is ${age}.`); } The above program will show the following error – Parameter cannot have question mark and initializer. Print Page Previous Next Advertisements ”;

TypeScript – Functions

TypeScript – Functions ”; Previous Next Functions in TypeScript are the building blocks of readable, maintainable, and reusable code. A function is a set of statements to perform a specific task. Functions organize the program into logical blocks of code. Once defined, functions may be called to access code. This makes the code reusable. Moreover, functions make it easy to read and maintain the program’s code. A function declaration tells the compiler about a function”s name, return type, and parameters. A function definition provides the actual body of the function. Sr.No Funtions & Description 1. Defining a Function A function definition specifies what and how a specific task would be done. 2. Calling a Function A function must be called so as to execute it. 3. Returning Functions Functions may also return value along with control, back to the caller. 4. Parameterized Function Parameters are a mechanism to pass values to functions. Optional Parameters Optional parameters can be used when arguments need not be compulsorily passed for a function’s execution. A parameter can be marked optional by appending a question mark to its name. The optional parameter should be set as the last argument in a function. The syntax to declare a function with optional parameter is as given below − function function_name (param1[:type], param2[:type], param3[:type]) Example: Optional Parameters function disp_details(id:number,name:string,mail_id?:string) { console.log(“ID:”, id); console.log(“Name”,name); if(mail_id!=undefined) console.log(“Email Id”,mail_id); } disp_details(123,”John”); disp_details(111,”mary”,”[email protected]”); The above example declares a parameterized function. Here, the third parameter, i.e., mail_id is an optional parameter. If an optional parameter is not passed a value during the function call, the parameter’s value is set to undefined. The function prints the value of mail_id only if the argument is passed a value. On compiling, it will generate following JavaScript code − //Generated by typescript 1.8.10 function disp_details(id, name, mail_id) { console.log(“ID:”, id); console.log(“Name”, name); if (mail_id != undefined) console.log(“Email Id”, mail_id); } disp_details(123, “John”); disp_details(111, “mary”, “[email protected]”); The above code will produce the following output − ID:123 Name John ID: 111 Name mary Email Id [email protected] Rest Parameters Rest parameters are similar to variable arguments in Java. Rest parameters don’t restrict the number of values that you can pass to a function. However, the values passed must all be of the same type. In other words, rest parameters act as placeholders for multiple arguments of the same type. To declare a rest parameter, the parameter name is prefixed with three periods. Any nonrest parameter should come before the rest parameter. Example: Rest Parameters 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) The function addNumbers() declaration, accepts a rest parameter nums. The rest parameter’s data type must be set to an array. Moreover, a function can have at the most one rest parameter. The function is invoked twice, by passing three and six values, respectively. The for loop iterates through the argument list, passed to the function and calculates their sum. On compiling, it will generate following JavaScript code − function addNumbers() { var nums = []; for (var _i = 0; _i < arguments.length; _i++) { nums[_i – 0] = arguments[_i]; } var i; var sum = 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); The output of the above code is as follows − sum of numbers 6 sum of numbers 50 Default Parameters Function parameters can also be assigned values by default. However, such parameters can also be explicitly passed values. Syntax function function_name(param1[:type],param2[:type] = default_value) { } Note − A parameter cannot be declared optional and default at the same time. Example: Default parameters 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) On compiling, it will generate following JavaScript code − //Generated by typescript 1.8.10 function calculate_discount(price, rate) { if (rate === void 0) { rate = 0.50; } var discount = price * rate; console.log(“Discount Amount: “, discount); } calculate_discount(1000); calculate_discount(1000, 0.30); Its output is as follows − Discount amount : 500 Discount amount : 300 The example declares the function, calculate_discount. The function has two parameters – price and rate. The value of the parameter rate is set to 0.50 by default. The program invokes the function, passing to it only the value of the parameter price. Here, the value of rate is 0.50 (default) The same function is invoked, but with two arguments. The default value of rate is overwritten and is set to the value explicitly passed. Anonymous Function Functions that are not bound to an identifier (function name) are called as anonymous functions. These functions are dynamically declared at runtime. Anonymous functions can accept inputs and return outputs, just as standard functions do. An anonymous function is usually not accessible after its initial creation. Variables can be assigned an anonymous function. Such an expression is called a function expression. Syntax var res = function( [arguments] ) { … } Example ─ A Simple Anonymous function var msg = function() { return “hello world”; } console.log(msg()) On compiling, it will generate the same code in JavaScript. It will produce the following output − hello world Example ─ Anonymous function with parameters var res = function(a:number,b:number) { return a*b; }; console.log(res(12,2)) The anonymous function returns the product of the values passed to it. On compiling, it will generate following JavaScript code − //Generated by typescript 1.8.10 var res = function (a, b) { return a * b; }; console.log(res(12, 2)); The output of the above code is as follows − 24 Function Expression and Function Declaration ─ Are they synonymous? Function expression and function declaration are not synonymous. Unlike a function expression, a function declaration is bound by the function name. The fundamental difference between the two is that, function declarations are parsed before their execution. On the other hand,

TypeScript – Function Constructor

TypeScript – The Function () Constructor ”; Previous Next The Function() Constructor TypeScript supports the built-in JavaScript constructor called Function() to defined a function. The Function() constructor dynamically creates a function object at runtime. You can define your function dynamically using Function() constructor along with the new operator. The Function() constructor can accept multiple arguments. All the arguments except the last one are names of parameters and the last argument is the function body of new function to be created. Syntax Following is the syntax to define a function using Function constructor along with new operator − let res = new Function(arg1, arg2, …, functionBody); let res = Function(arg1, arg2, …, functionBody); Function() can be called with or without new. Both syntaxes will create a new Function instance. All the arguments, i.e., arg1, arg2, …, functionBody, are strings. Arguments arg1, arg2, …, – These are optional arguments treated as the names of the parameters in the function to be created. functionBody − This argument contains the statements in function definition of the new function to be created. All the arguments except the last one are optional. The last argument is required. If you are passing only a single argument, then it will be treated as function body. Notice that the Function() constructor is not passed any argument that specifies a name for the function it creates. The unnamed functions created with the Function() constructor are called anonymous functions. The new Function() is a call to the constructor which in turn creates and returns a function reference. Examples Let”s understand the Function constructor with help of some example programs in TypeScript. Example 1: Creating a simple function without parameters In the example below, the Function() constructor takes only single argument. This argument is treated as the function body. const greet = new Function(“return ”Welcome to Tutorials Point!””); console.log(greet()); On compiling TypeScript generate the same code in JavaScript. The output of the above example code is as follows − Welcome to Tutorials Point! Example 2: Creating a simple function with parameters In the example below, we call the Function() constructor passing three arguments, “x”, “y” and “return x + y”. The first two arguments are the names of the parameters of the new function instance, i.e., resFunction. const resFucntion = new Function(“x”, “y”, “return x + y”); let sum = resFucntion(5, 10); console.log(sum); On compiling, TypeScript will generate the same code in JavaScript. The compiled JavaScript code will produce the following output − 15 Example 3: Creating a function instance from a function expression In the example below, we define a function sum with function expression and pass it to the Function() constructor as a part of the parameter (function body). Here the function expression requires a return statement with the function”s name. const add = new Function( “const sum = function (a, b) {return a+ b}; return sum”, )(); console.log(add(2,3)); TypeScript compiler will generate the same code in JavaScript. The JavaScript code will produce the following output − 5 Example 4: Creating a function instance from a function declaration In the example below, we pass a function declaration as an argument to the Function constructor. The function declaration doesn’t need a return statement with the function” name. const sayHello = new Function( “return function (name) { return `Hello, ${name}` }”, )(); console.log(sayHello(“Shahid”)); On compiling, it will generate the same code in JavaScript. The output of the above example code is as follows − Hello Shahid The Function constructor in TypeScript can be used to define a function at execution time, but you should use it with caution as it can lead to vulnerabilities in the code. Print Page Previous Next Advertisements ”;

TypeScript – Overview

TypeScript – Overview ”; Previous Next JavaScript was introduced as a language for the client side. The development of Node.js has marked JavaScript as an emerging server-side technology too. However, as JavaScript code grows, it tends to get messier, making it difficult to maintain and reuse the code. Moreover, its failure to embrace the features of Object Orientation, strong type checking and compile-time error checks prevents JavaScript from succeeding at the enterprise level as a full-fledged server-side technology. TypeScript was presented to bridge this gap. What is TypeScript? By definition, “TypeScript is JavaScript for application-scale development.” TypeScript is a strongly typed, object oriented, compiled language. It was designed by Anders Hejlsberg (designer of C#) at Microsoft. TypeScript is both a language and a set of tools. TypeScript is a typed superset of JavaScript compiled to JavaScript. In other words, TypeScript is JavaScript plus some additional features. Features of TypeScript TypeScript is just JavaScript. TypeScript starts with JavaScript and ends with JavaScript. Typescript adopts the basic building blocks of your program from JavaScript. Hence, you only need to know JavaScript to use TypeScript. All TypeScript code is converted into its JavaScript equivalent for the purpose of execution. TypeScript supports other JS libraries. Compiled TypeScript can be consumed from any JavaScript code. TypeScript-generated JavaScript can reuse all of the existing JavaScript frameworks, tools, and libraries. JavaScript is TypeScript. This means that any valid .js file can be renamed to .ts and compiled with other TypeScript files. TypeScript is portable. TypeScript is portable across browsers, devices, and operating systems. It can run on any environment that JavaScript runs on. Unlike its counterparts, TypeScript doesn’t need a dedicated VM or a specific runtime environment to execute. TypeScript and ECMAScript The ECMAScript specification is a standardized specification of a scripting language. There are six editions of ECMA-262 published. Version 6 of the standard is codenamed “Harmony”. TypeScript is aligned with the ECMAScript6 specification. TypeScript adopts its basic language features from the ECMAScript5 specification, i.e., the official specification for JavaScript. TypeScript language features like Modules and class-based orientation are in line with the EcmaScript 6 specification. Additionally, TypeScript also embraces features like generics and type annotations that aren’t a part of the EcmaScript6 specification. Why Use TypeScript? TypeScript is superior to its other counterparts like CoffeeScript and Dart programming languages in a way that TypeScript is extended JavaScript. In contrast, languages like Dart, CoffeeScript are new languages in themselves and require language-specific execution environment. The benefits of TypeScript include − Compilation − JavaScript is an interpreted language. Hence, it needs to be run to test that it is valid. It means you write all the codes just to find no output, in case there is an error. Hence, you have to spend hours trying to find bugs in the code. The TypeScript transpiler provides the error-checking feature. TypeScript will compile the code and generate compilation errors, if it finds some sort of syntax errors. This helps to highlight errors before the script is run. Strong Static Typing − JavaScript is not strongly typed. TypeScript comes with an optional static typing and type inference system through the TLS (TypeScript Language Service). The type of a variable, declared with no type, may be inferred by the TLS based on its value. TypeScript supports type definitions for existing JavaScript libraries. TypeScript Definition file (with .d.ts extension) provides definition for external JavaScript libraries. Hence, TypeScript code can contain these libraries. TypeScript supports Object Oriented Programming concepts like classes, interfaces, inheritance, etc. Components of TypeScript At its heart, TypeScript has the following three components − Language − It comprises of the syntax, keywords, and type annotations. The TypeScript Compiler − The TypeScript compiler (tsc) converts the instructions written in TypeScript to its JavaScript equivalent. The TypeScript Language Service − The “Language Service” exposes an additional layer around the core compiler pipeline that are editor-like applications. The language service supports the common set of a typical editor operations like statement completions, signature help, code formatting and outlining, colorization, etc. Declaration Files When a TypeScript script gets compiled, there is an option to generate a declaration file (with the extension .d.ts) that functions as an interface to the components in the compiled JavaScript. The concept of declaration files is analogous to the concept of header files found in C/C++. The declaration files (files with .d.ts extension) provide intellisense for types, function calls, and variable support for JavaScript libraries like jQuery, MooTools, etc. Print Page Previous Next Advertisements ”;

TypeScript – While Loop

TypeScript – While Loop ”; Previous Next The while loop executes the instructions each time the condition specified evaluates to true. In other words, the loop evaluates the condition before the block of code is executed. As a superset of JavaScript, TypeScript inherits and expands upon JavaScript’s features including different types of loops. The while loop is an entry-controlled loop. In an entry-controlled loop, the condition is checked first and if the condition is true then the statements within the loop body are executed. While in an exit-controlled loop, the condition is checked after executing the loop body. The do…while loop is an example of the exit-controlled loop. Syntax The syntax of the while loop in TypeScript is as follows – while(condition) { // statements if the condition is true } Flow Diagram The flow diagram of the while loop looks as follows – Here is a breakdown of the while loop”s behavior – Condition evaluation − the while loop evaluates the condition before each iteration. Execution − if the condition evaluates to true, the code block within the loop body is executed. Iteration − After code block execution is finished, the loop jumps back to the first step (condition evaluation) to check if another iteration is required. Example: While loop var num:number = 5; var factorial:number = 1; while(num >=1) { factorial = factorial * num; num–; } console.log(“The factorial is “+factorial); The above code snippet uses a while loop to calculate the factorial of the value in the variable num. On compiling, it will generate the following JavaScript code − var num = 5; var factorial = 1; while (num >= 1) { factorial = factorial * num; num–; } console.log(“The factorial is ” + factorial); It produces the following output − The factorial is 120 While loop with a break statement You can use a combination of an if statement and a break statement to terminate a while loop prematurely. The if statement checks a condition. If the condition evaluates to true, the break statement forces the while loop to exit, skipping any remaining code within the loop body. Example In the following example, the loop iterates until i reaches to 3. When the value of i becomes 3, the condition (i === 3) is true and break statement terminates the loop. var i: number = 0; while (i < 5) { if (i === 3) { break; } console.log(i); i++; } On compiling, it will generate the following JavaScript code. var i = 0; while (i < 5) { if (i === 3) { break; } console.log(i); i++; } The output of the above example code is as follows – 0 1 2 While loop vs. for loop You should use a for loop when the number of iterations is fixed and known. When the number of iterations is not known, you should use the while loop. We can convert a for loop to the while loop by omitting the first and last expression in the for loop. Let’s take the example of the following for loop – for (var i = 0; i < 5; i++){ console.log(i) } The output is as follows- 0 1 2 3 4 We can modify the above example code as follows – var i = 0 for ( ; i < 5; ){ console.log(i); i++; } It will also produce the same output as the above code – 0 1 2 3 4 In the above example, we omitted the first and third expressions in the for loop. It is similar to the while loop statement. var i = 0 while(i < 5){ console.log(i); i++; } It will also produce the same output as the above two examples. 0 1 2 3 4 Notice that a for loop without first and third expressions is similar to the while loop. Print Page Previous Next Advertisements ”;

TypeScript – Literal Types

TypeScript – Literal Types ”; Previous Next In TypeScript, literal types are subtypes of the primitive data types. The literal types allow you to specify the exact value the variable can contain. There are three types of the literal types in TypeScript. String literal types Numeric literal types Boolean literal types Each of them allows you to store the specific value in the variable rather than storing the generalized string, numeric, or boolean value. Syntax You can follow the syntax below to use the literal types in TypeScript. type lit_type = type_1 | type_2 | type_3 | … In the above syntax, ”type” is a keyword to create a type alias. The ”lit_type” is the name of the type. The ”type_1”, ”type_2”, and “type_3” are values of type string, Boolean, or number. String Literal Types The string literal type allows you to define a set of specific values from which a variable or function parameter should contain any value. Example In the code below, we have created the ”Direction” type which contains all 4 directions in string format. The type of the move() function parameter is Direction so it accepts any value from the 4 directions. If you try to pass any value other than 4 directions as an argument, it throws an error. // Defining a custom-type Direction type Direction = “North” | “East” | “South” | “West”; // Defining a function move that takes a single argument of type Direction. function move(direction: Direction) { console.log(`Moving in the direction: ${direction}`); } move(“North”); move(“East”); // move(“Northeast”); // Error: Argument of type ””Northeast”” is not assignable to parameter of type ”Direction”. On compiling, it will generate the following JavaScript code. // Defining a function move that takes a single argument of type Direction. function move(direction) { console.log(`Moving in the direction: ${direction}`); } move(“North”); move(“East”); // move(“Northeast”); // Error: Argument of type ””Northeast”” is not assignable to parameter of type ”Direction”. The output of the above code is as follows – Moving in the direction: North Moving in the direction: East Numeric Literal Types Numeric literal types are similar to string literals but allow you to specify exact numeric values as allowed types. Example In the code below, the ”SmallPrimes” type contains the small prime numbers till 11 as a value. The type of the ”prime” variable is ”SmallPrimes”. So, it can contain any value from 2, 3, 5, 7, or 11 only. type SmallPrimes = 2 | 3 | 5 | 7 | 11; let prime: SmallPrimes; prime = 7; console.log(prime); // 7 // prime = 4; // Error: Type ”4” is not assignable to type ”SmallPrimes”. On compiling, it will generate the following JavaScript code. let prime; prime = 7; console.log(prime); // 7 // prime = 4; // Error: Type ”4” is not assignable to type ”SmallPrimes”. The output of the above code is follows – 7 Combined Literal Types You can combine different types of literals (string, numeric, boolean) using union types to allow a variable to hold a set of specified values. Example In the code below, the ”MixedLiterals” type contains the “click”, 404, and true values. The action variable can contain any singl value from the 3 values of the ”MixedLiterals” type. // Mixed type literals type MixedLiterals = “Click” | 404 | true; let action: MixedLiterals; action = “Click”; // Valid console.log(action); action = 404; // Valid console.log(action); action = true; // Valid console.log(action); // action = “Other”; // Error: Type ””Other”” is not assignable to type ”MixedLiterals”. On compiling, it will generate the following JavaScript code. let action; action = “Click”; // Valid console.log(action); action = 404; // Valid console.log(action); action = true; // Valid console.log(action); // action = “Other”; // Error: Type ””Other”” is not assignable to type ”MixedLiterals”. The output of the above code is as follows – Click 404 true Use Cases for Literal Types There are multiple use cases of literal types. However, we will look into some real-time use cases of the literal types. Configuration − It is used to define the particular configuration of variables or function parameters that take only specific values. State Management − Type literals can be used for state management. API Response Handling − It is used to handle the API response based on the API response status. Literal types in TypeScript enhance the type safety of your applications by allowing you to specify exactly what values are acceptable. It also helps developers maintain the code complexity and improve the readability. Print Page Previous Next Advertisements ”;

TypeScript – Strings

TypeScript – Strings ”; Previous Next In TypeScript, a string represents a sequence of characters. The string type is a fundamental data type in TypeScript. Strings are important to hold data that can be represented in text form. Like JavaScript, TypeScript also supports both string primitives and String objects. The String object lets you work with a series of characters. It wraps the string primitive data type with a number of helper methods. You can invoke methods on primitive strings because TypeScript automatically wraps the string primitive and call the methods on wrapper object. The same applies to properties also. Creating Strings Strings in TypeScript can be created as primitives from string literals or as objects using the String() constructor. You can use the following syntax to create a String object in TypeScript − cost str = new String(value); Here str is the newly created String object and value is a series of characters. You can create string primitives using single quote, double quotes and backtick. let str1: string = ”a string primitive”; let str2: string = “another string”; let str3: string = `yet another string`; The string primitives can also be created using the String() function without new keyword. let str: string = String(value); ”string” is a primitive, but ”String” is a wrapper object. Prefer using ”string” when possible. String Properties A list of the methods available in String object along with their description is given below − S.No. Property & Description 1. Constructor Returns a reference to the String function that created the object. 2. Length Returns the length of the string. 3. Prototype The prototype property allows you to add properties and methods to an object. String Methods A list of the methods available in String object along with their description is given below − S.No. Method & Description 1. charAt() Returns the character at the specified index. 2. charCodeAt() Returns a number indicating the Unicode value of the character at the given index. 3. concat() Combines the text of two strings and returns a new string. 4. indexOf() Returns the index within the calling String object of the first occurrence of the specified value, or -1 if not found. 5. lastIndexOf() Returns the index within the calling String object of the last occurrence of the specified value, or -1 if not found. 6. localeCompare() Returns a number indicating whether a reference string comes before or after or is the same as the given string in sort order. 7. match() Used to match a regular expression against a string. 8. replace() Used to find a match between a regular expression and a string, and to replace the matched substring with a new substring. 9. search() Executes the search for a match between a regular expression and a specified string. 10. slice() Extracts a section of a string and returns a new string. 11. split() Splits a String object into an array of strings by separating the string into substrings. 12. substr() Returns the characters in a string beginning at the specified location through the specified number of characters. 13. substring() Returns the characters in a string between two indexes into the string. 14. toLocaleLowerCase() The characters within a string are converted to lower case while respecting the current locale. 15. toLocaleUpperCase() The characters within a string are converted to upper case while respecting the current locale. 16. toLowerCase() Returns the calling string value converted to lower case. 17. toString() Returns a string representing the specified object. 18. toUpperCase() Returns the calling string value converted to uppercase. 19. valueOf() Returns the primitive value of the specified object. Examples Let’s understand the string types with the help of some examples in TypeScript. Example: Creating String Primitives In the example below, we use single quote, double quote and backtick to create the primitive strings str1, str2 and str3 respectively. let str1: string = ”a string primitive”; console.log(str1); let str2: string = “another string”; console.log(str2); let str3: string = `yet another string`; console.log(str3); On compiling, it will generate the following JavaScript code. let str1 = ”a string primitive”; console.log(str1); let str2 = “another string”; console.log(str2); let str3 = `yet another string`; console.log(str3); The output of the above example code is as follows − a string primitive another string yet another string Example: Creating String Objects Here we create a String object using the String() constructor with new keyword. const email = new String(”[email protected]”); console.log(email); console.log(typeof email); On compiling, it will generate the following JavaScript code. const email = new String(”[email protected]”); console.log(email); console.log(typeof email); The output of the above example code is as follows − [email protected] object Example: Concatenating TypeScript strings To concatenate two string, we can use + operator. Here, we concatenate two strings str1 and str2 and display the result in the console. let str1: string = “Hello “; let str2: string = “World!”; let str3: string = str1 + str2; console.log(str3); On compiling, it will generate the following JavaScript code. let str1 = “Hello “; let str2 = “World!”; let str3 = str1 + str2; console.log(str3); The output of the above example code is as follows – Hello World! Example: Accessing string elements using indexing In the example below, we access the string characters from the 1st and 6th indices. let message: string = “Hello World!”; console.log(“Character at index 1 is => ” + message[1]); console.log(“Character at index 6 is => ” + message[6]); On compiling, it will generate the following JavaScript code. let message = “Hello World!”; console.log(“Character at index 1 is => ” + message[1]); console.log(“Character at index 6 is => ” + message[6]); The output of the above example code is as follows − Character at index 1 is => e Character at index 6 is => W Example: String vs. string in TypeScript In TypeScript, type ”String” is a wrapper object and type ”string” is a primitive type. These both types can’t be assigned to each other. In the example below, we tried to assign a string object to a variable

TypeScript – Never

TypeScript – Never ”; Previous Next The never type The never type in TypeScript represents the values that can never occur. For example, the return type of a function that throws an error is never. function funcName(): never{ // it throws an exception or never returns } You cannot assign a value to a variable of never type – let x: never; x = 10; // throw error The above TypeScript code snippet will throw the following errors – Type ”number” is not assignable to type ”never”. You can use the never type as the return type of a function that never returns or always throws an exception. A function that never stops executing – function infiniteLoop(): never{ for(;;){} } Another example of function that never stops executing – function infiniteLoop(): never{ while (true) { } } Variables also acquire the type never when narrowed by any type guards that can never be true. The never type is used when we have exhausted all possible value and we don”t have anything to assign. function check(value: string | number) { if (typeof value === ”string”) { return “value is string”; } else { return “value is number”; } // here, not a string or number // “value” can”t occur here, so it”s type “never” } The never type is a subtype of, and assignable to, every type; however, no type is a subtype of, or assignable to, never (except never itself). Even any isn’t assignable to never. You can annotate a variable with never type, but it is very uncommon – function showError(): never{ throw new Error(“Error message from function with never as return type.”); } let x: never = showError(); In the above Typescript code snippet, variable x is annotated with the never type. The variable x is assigned showError() function that itself has the never as return type. void vs. never In TypeScript, a variable of void type can store undefined as a value. On the other hand, never can”t store any value. let val1: void = undefined; let val2: never = undefined; // error: Type ”undefined” is not assignable to type ”never”. We know that if a function in TypeScript does not return any value, it returns undefined. We generally annotate the type of return type of such function with void. Look at the below example, function greet(): void{ console.log(“Welcome to tutorials Point”); } let msg: void = greet(); console.log(msg); In the above example, we defined a function greet() that doesn”t return any value. When we call the function, the return value is undefined. On compiling, it will generate the following JavaScript code. function greet() { console.log(“Welcome to tutorials Point”); } let msg = greet(); console.log(msg); The output of the above code is as follows – Undefined Print Page Previous Next Advertisements ”;

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 ”;