From JavaScript To TypeScript

Migrating from JavaScript to TypeScript ”; Previous Next TypeScript is a superset of JavaScript and provides more features than JavaScript. The main purpose of using TypeScript in any project instead of JavaScript is to achieve type safety as TypeScript allows defining types for each variable, function parameters, function return type, etc. Furthermore, TypeScript also has features like static typing and supports classes, interfaces, modules, and other high-level features that are not supported by JavaScript. Here, you will learn to migrate your JavaScript code to TypeScript. Why Migrate from JavaScript to TypeScript? Here are a few reasons why anyone should use TypeScript over JavaScript: Type Safety: TypeScript’s core feature is its ability to perform static type checking. Improved Code Quality: TypeScript can catch errors early in the development process, which can save costs and time in software development. Advanced features: TypeScript supports advanced features like interfaces, etc. which are not supported by JavaScript. Scalability: Easier to manage and scale large codebases with TypeScript. Steps to Migrate from JavaScript to TypeScript You can follow the below steps to migrate your JavaScript code to TypeScript: Pre-requisite You should have a JavaScript file containing the JavaScript code. Step 1: Setting Up Your Environment If you haven’t installed TypeScript, you can execute the below command in the terminal to install TypeScript: npm install -g typescript Step 2: Add tsconfig.json File in the Project The main part of converting the JavaScript project into the TypeScript project is adding the tsconfig.json file in the root directory of the project. The tsconfig.json file contains a single JSON object containing various properties. It defines the configuration to compile the TypeScript code into plain JavaScript code. You can create a new tsconfig.json file and add the below code to that: { “compileOnSave”: true, “compilerOptions”: { “target”: “es6”, “lib”: [ “es6”, “dom” ], “module”: “commonjs”, } “include”: [ “src/**/*” ], } However, you can also remove some properties or add them in the tsconfig.json file according to your requirements. Step 3: Convert JavaScript Files to TypeScript Now you are ready to use TypeScript files. TypeScript compiler compiles only TypeScript files (.ts and .tsx). Rename one of the .js files to .ts. If your file includes JSX, then rename it to .tsx. After renaming the file, you may notice that TypeScript files may contain some type errors. To handle type errors, we perform type annotations. Add Type Annotations After renaming the JavaScript files to TypeScript, we start adding type annotations to variables, function parameters, and return types. This will help the TypeScript compiler catch potential errors. Let’s take an example. Suppose, we have the below code in the JavaScript file: function add(a, b) { return a + b; } The above code contains the add() function which takes two variables ‘a’ and ‘b’ as parameters and returns the sum of them. To convert the above code to TypeScript, you need to add types for the function parameters and specify the return type for the function. function add(a: number, b: number): number { return a + b; } Here, we have used the number type for both parameters and the return type of the function. Step 4: Solve Errors and Install External Libraries After converting the JavaScript code into TypeScript, make sure to solve any errors given in the code editor. Otherwise, you will also get an error while compiling the TypeScript code into plain JavaScript code. If you are using external libraries in the JavaScript project, you can use the Node Package Manager (NPM) to install the libraries in the TypeScript project. If you don’t install these external libraries, the compiler will throw an error. Step 5: Compile the TypeScript Code After solving the errors, execute the below command in the terminal to compile the TypeScript code: npx tsc filename In the above command, you can replace filename with the actual name of the TypeScript file. After executing the command, it will generate a JavaScript file with the same name as the TypeScript file. This JavaScript file can be used like a normal JavaScript file with HTML or executed using NodeJS. This lesson has explained the basic steps to convert your JavaScript project into TypeScript. However, with the help of these steps, you can also convert a complex JavaScript project into TypeScript. Print Page Previous Next Advertisements ”;

TypeScript – Nested If Statements

TypeScript – Nested if statements ”; Previous Next A nested if statement in TypeScript is an if statement that is present inside the body of another if or else statement. The else…if ladder is a type of nested if statement. The nested if statement or else…if ladder is useful to test multiple conditions. Its syntax is given below − Syntax if (boolean_expression1) { //statements if the expression1 evaluates to true } else if (boolean_expression2) { //statements if the expression2 evaluates to true } else if (boolean_expression3) { //statements if the expression3 evaluates to false } else { //statements if all three boolean expressions result to false } When using if…else…if and else statements, there are a few points to keep in mind. An if can have zero or one else”s and it must come after any else…if”s. An if can have zero to many else…if”s and they must come before the else. Once an else…if succeeds, none of the remaining else…if”s or else”s will be tested. Example: else…if ladder var num:number = 2 if(num > 0) { console.log(num&plus;” is positive”) } else if(num < 0) { console.log(num+” is negative”) } else { console.log(num+” is neither positive nor negative”) } The snippet displays whether the value is positive, negative or zero. On compiling, it will generate the following JavaScript code − //Generated by typescript 1.8.10 var num = 2; if (num > 0) { console.log(num + ” is positive”); } else if (num < 0) { console.log(num + ” is negative”); } else { console.log(num + ” is neither positive nor negative”); } Here is the output of the above code − 2 is positive Print Page Previous Next Advertisements ”;

TypeScript – Type Inference

TypeScript – Type Inference ”; Previous Next Type inference is a feature in TypeScript that allows the compiler to automatically determine (infer) the type of a variable, function or expression. TypeScript is an optionally static type programming language. You can declare variables, expressions, or functions without explicitly annotating their types. The compiler will automatically determine the types at the compile time. The type inference can be done on the basis of a number of factors, including – The type of values assigned to the variables. The type of function parameters or arguments passed to the function. The type of return value of the function. The types of the object and properties. Let”s take a simple example as follows – let x = 5; let y = “Hello World!”; In the above code, the TypeScript compiler can infer that the type of variable x is number. This is because the variable x is being assigned a number. The compiler can also infer the type of y is string because the y is being assigned a string. In the above example, TypeScript automatically infers the types of variables based on the values assigned to them. Variable or Member Initialization The type inference can be inferred using the variable and member initialization. The TypeScript compiler infers the type of the variable from the initialized value. Example Let”s take an example of variable initialization as follows – let x = 20; let y = “Hello World!”; let z = true; console.log(“type of x: “, typeof x); console.log(“type of y: “, typeof y); console.log(“type of z: “, typeof z); On compilation, it will generate the same JavaScript code. The output of the above example code is as follows – type of x: number type of y: string type of z: boolean Let’s have an example of object member initialization – class Person { name = “Shahid”; age = 35; } const p = new Person(); // Prints name and age console.log(`${p.name}, ${p.age}`); On compilation, it will generate following JavaScript code. class Person { constructor() { this.name = “Shahid”; this.age = 35; } } const p = new Person(); // Prints name and age console.log(`${p.name}, ${p.age}`); The output of the above code is as follows – Shahid, 35 Function Default Parameter The typescript compiler can also infer the type of the function parameters when the parameters are initialized with default values. In the below example, the parameters x and y are initialized with default values. The compiler infers the type of x and y as number. This is because the initialized values are numbers. function add(x = 10, y = 30){ return x + y; } let res = add(2,3); console.log(res); On compilation, it will generate the same code in JavaScript. The output of the above example code is as follows – 5 Now let”s try to pass arguments as string values. let res2 = add(”2”, ”3”); The type of the parameters of the function add are inferred as number so when we pass arguments of type string to the function, it shows the following error – Argument of type ”string” is not assignable to parameter of type ”number”. Function Return Type The TypeScript compiler infers the type of the return type of the function based on the type of the return value. If the function doesn”t return any value, then the return type is void. In the example below, the function add accepts the two numbers and return their sum. As the sum of two numbers are number, so the type of return value is number. Hence the compiler infers the return type of the function add as number. function add(x: number, y: number){ return x + y; } let res1: number = add(2,3); console.log(res1); When we assign the return value of the function add to variable (res2) of type string, it will show an error. let res2: string = add(2,3); The error is as follows – Type ”number” is not assignable to type ”string”. This is because the return type of the function add is number and we are assigning it to variable of string type. Best Common Type: The Union Type Type inference with variable initialization, function default parameters and return type is straightforward. When TypeScript infers a type from multiple expressions, the type of the expressions is determined as the “best common type”. Let”s understand this with the help of an example – const a = [5, 10, “TypeScript”]; In the above example, the array contains values – 5, 10, and “TypeScript”. To infer the type of the array, we must consider the type of each element. Here, we have choices for the type of the array as number, and string. The inferred type of the array should be the best common type for each value in the array. The best common type has to be chosen from the provided candidate type. If there is no super type of all candidate types, the union type is used. Hence the inferred type of the above array is – (number | string)[] The above array can contain values of types number, and string only. If you try to add a value of type different from number and string, it will show an error. Let”s try to add a boolean value to the array. const a = [5, 10, “TypeScript”]; a.push(true); The above code will show the following compilation error – Argument of type ”boolean” is not assignable to parameter of type ”string | number”. Contextual Typing Contextual typing is a feature in TypeScript that allows the compiler to infer the type of variable, parameter or expression based on the context where they are used. For example, window.onmousedown = function (mouseEvent) { console.log(mouseEvent.button); } In the above example, the TypeScript infers the type the function expression on right hand side of the assignment using the type of the Window.onmousedown function. So it is able to infer the type of mouseEvent parameter as MouseEvent. This way TypeScript infers that mouseEvent has a

TypeScript – Modules

TypeScript – Modules ”; Previous Next A module is designed with the idea to organize code written in TypeScript. Modules are broadly divided into − Internal Modules External Modules Internal Module Internal modules came in earlier version of Typescript. This was used to logically group classes, interfaces, functions into one unit and can be exported in another module. This logical grouping is named namespace in latest version of TypeScript. So internal modules are obsolete instead we can use namespace. Internal modules are still supported, but its recommended to use namespace over internal modules. Internal Module Syntax (Old) module TutorialPoint { export function add(x, y) { console.log(x+y); } } Namespace Syntax (New) namespace TutorialPoint { export function add(x, y) { console.log(x + y);} } JavaScript generated in both cases are same var TutorialPoint; (function (TutorialPoint) { function add(x, y) { console.log(x + y); } TutorialPoint.add = add; })(TutorialPoint || (TutorialPoint = {})); External Module External modules in TypeScript exists to specify and load dependencies between multiple external js files. If there is only one js file used, then external modules are not relevant. Traditionally dependency management between JavaScript files was done using browser script tags (<script></script>). But that’s not extendable, as its very linear while loading modules. That means instead of loading files one after other there is no asynchronous option to load modules. When you are programming js for the server for example NodeJs you don’t even have script tags. There are two scenarios for loading dependents js files from a single main JavaScript file. Client Side – RequireJs Server Side – NodeJs Selecting a Module Loader To support loading external JavaScript files, we need a module loader. This will be another js library. For browser the most common library used is RequieJS. This is an implementation of AMD (Asynchronous Module Definition) specification. Instead of loading files one after the other, AMD can load them all separately, even when they are dependent on each other. Defining External Module When defining external module in TypeScript targeting CommonJS or AMD, each file is considered as a module. So it’s optional to use internal module with in external module. If you are migrating TypeScript from AMD to CommonJs module systems, then there is no additional work needed. The only thing you need to change is just the compiler flag Unlike in JavaScript there is an overhead in migrating from CommonJs to AMD or vice versa. The syntax for declaring an external module is using keyword ‘export’ and ‘import’. Syntax //FileName : SomeInterface.ts export interface SomeInterface { //code declarations } To use the declared module in another file, an import keyword is used as given below. The file name is only specified no extension used. import someInterfaceRef = require(“./SomeInterface”); Example Let’s understand this using an example. // IShape.ts export interface IShape { draw(); } // Circle.ts import shape = require(“./IShape”); export class Circle implements shape.IShape { public draw() { console.log(“Cirlce is drawn (external module)”); } } // Triangle.ts import shape = require(“./IShape”); export class Triangle implements shape.IShape { public draw() { console.log(“Triangle is drawn (external module)”); } } // TestShape.ts import shape = require(“./IShape”); import circle = require(“./Circle”); import triangle = require(“./Triangle”); function drawAllShapes(shapeToDraw: shape.IShape) { shapeToDraw.draw(); } drawAllShapes(new circle.Circle()); drawAllShapes(new triangle.Triangle()); The command to compile the main TypeScript file for AMD systems is − tsc –module amd TestShape.ts On compiling, it will generate following JavaScript code for AMD. File:IShape.js //Generated by typescript 1.8.10 define([“require”, “exports”], function (require, exports) { }); File:Circle.js //Generated by typescript 1.8.10 define([“require”, “exports”], function (require, exports) { var Circle = (function () { function Circle() { } Circle.prototype.draw = function () { console.log(“Cirlce is drawn (external module)”); }; return Circle; })(); exports.Circle = Circle; }); File:Triangle.js //Generated by typescript 1.8.10 define([“require”, “exports”], function (require, exports) { var Triangle = (function () { function Triangle() { } Triangle.prototype.draw = function () { console.log(“Triangle is drawn (external module)”); }; return Triangle; })(); exports.Triangle = Triangle; }); File:TestShape.js //Generated by typescript 1.8.10 define([“require”, “exports”, “./Circle”, “./Triangle”], function (require, exports, circle, triangle) { function drawAllShapes(shapeToDraw) { shapeToDraw.draw(); } drawAllShapes(new circle.Circle()); drawAllShapes(new triangle.Triangle()); }); The command to compile the main TypeScript file for Commonjs systems is tsc –module commonjs TestShape.ts On compiling, it will generate following JavaScript code for Commonjs. File:Circle.js //Generated by typescript 1.8.10 var Circle = (function () { function Circle() { } Circle.prototype.draw = function () { console.log(“Cirlce is drawn”); }; return Circle; })(); exports.Circle = Circle; File:Triangle.js //Generated by typescript 1.8.10 var Triangle = (function () { function Triangle() { } Triangle.prototype.draw = function () { console.log(“Triangle is drawn (external module)”); }; return Triangle; })(); exports.Triangle = Triangle; File:TestShape.js //Generated by typescript 1.8.10 var circle = require(“./Circle”); var triangle = require(“./Triangle”); function drawAllShapes(shapeToDraw) { shapeToDraw.draw(); } drawAllShapes(new circle.Circle()); drawAllShapes(new triangle.Triangle()); Output Cirlce is drawn (external module) Triangle is drawn (external module) Print Page Previous Next Advertisements ”;

TypeScript – Utility Types

TypeScript – Utility Types ”; Previous Next TypeScript allows us to create a new type from the existing types, and we can use the utility types for such transformation. There are various utility types that exist in TypeScript, and we can use any utility type according to our requirements of the type transformation. Let”s discus the different utility types with examples in TypeScript. Partial Type in TypeScript The Partial utility type transforms all the properties of the current type to optional. The meaning of the partial is either all, some, or none. So, it makes all properties optional, and users can use it while refactoring the code with objects. Example In the example below, we have created the Type containing some optional properties. After that, we used the Partial utility type to create a partialType object. Users can see that we haven’t initialized all the properties of the partialType object, as all properties are optional. type Type = { prop1: string; prop2: string; prop3: number; prop4?: boolean; }; let partialType: Partial<Type> = { prop1: “Default”, prop4: false, }; console.log(“The value of prop1 is ” + partialType.prop1); console.log(“The value of prop2 is ” + partialType.prop2); On compiling, it will generate the following JavaScript code − var partialType = { prop1: “Default”, prop4: false }; console.log(“The value of prop1 is ” + partialType.prop1); console.log(“The value of prop2 is ” + partialType.prop2); Output The above code will produce the following output − The value of prop1 is Default The value of prop2 is undefined Required Type in TypeScript The Required utility type allows us to transform type in such a way that it makes all properties of the type required. When we use the Required utility type, it makes all optional properties to required properties. Example In this example, Type contains the prop3 optional property. After transforming the Type using the Required utility operator, prop3 also became required. If we do not assign any value to the prop3 while creating the object, it will generate a compilation error. type Type = { prop1: string; prop2: string; prop3?: number; }; let requiredType: Required<Type> = { prop1: “Default”, prop2: “Hello”, prop3: 40, }; console.log(“The value of prop1 is ” + requiredType.prop1); console.log(“The value of prop2 is ” + requiredType.prop2); On compiling, it will generate the following JavaScript code − var requiredType = { prop1: “Default”, prop2: “Hello”, prop3: 40 }; console.log(“The value of prop1 is ” + requiredType.prop1); console.log(“The value of prop2 is ” + requiredType.prop2); Output The above code will produce the following output − The value of prop1 is Default The value of prop2 is Hello Pick Type in TypeScript The Pick utility type allows us to pick a type of properties of other types and create a new type. Users need to use the key of the types in the string format to pick the key with their type to include in the new type. Users should use the union operator if they want to pick multiple keys with their type. Example In the example below, we have picked the color and id properties from type1 and created the new type using the Pick utility operator. Users can see that when they try to access the size property of the newObj, it gives an error as a type of newObj object doesn’t contain the size property. type type1 = { color: string; size: number; id: string; }; let newObj: Pick<type1, “color” | “id”> = { color: “#00000”, id: “5464fgfdr”, }; console.log(newObj.color); // This will generate a compilation error as a type of newObj doesn”t contain the size property // console.log(newObj.size); On compiling, it will generate the following JavaScript code − var newObj = { color: “#00000”, id: “5464fgfdr” }; console.log(newObj.color); // This will generate a compilation error as a type of newObj doesn”t contain the size property // console.log(newObj.size); Output The above code will produce the following output − #00000 Omit Type in TypeScript The Omit removes the keys from the type and creates a new type. It is the opposite of the Pick. Whatever key we use with the Omit utility operator removes those keys from the type and returns a new type. Example In this example, we have omitted the color and id properties from the type1 using the Omit utility type and created the omitObj object. When a user tries to access the color and id properties of omitObj, it will generate an error. type type1 = { color: string; size: number; id: string; }; let omitObj: Omit<type1, “color” | “id”> = { size: 20, }; console.log(omitObj.size); // This will generate an error // console.log(omitObj.color); // console.log(omitObj.id) On compiling, it will generate the following JavaScript code − var omitObj = { size: 20 }; console.log(omitObj.size); // This will generate an error // console.log(omitObj.color); // console.log(omitObj.id) Output The above code will produce the following output − 20 Readonly Type in TypeScript We can use the Readonly utility type to make all types read-only properties, making all properties immutable. So, we can’t assign any value to the readonly properties after initializing for the first time. Example In this example, keyboard_type contains three different properties. We have used the Readonly utility type to make all properties of keyboard objects read-only. The read-only property means we can access it to read values, but we can’t modify or reassign them. type keyboard_type = { keys: number; isBackLight: boolean; size: number; }; let keyboard: Readonly<keyboard_type> = { keys: 70, isBackLight: true, size: 20, }; console.log(“Is there backlight in the keyboard? ” + keyboard.isBackLight); console.log(“Total keys in the keyboard are ” + keyboard.keys); // keyboard.size = 30 // this is not allowed as all properties of the keyboard are read-only On compiling, it will generate the following JavaScript code − var keyboard = { keys: 70, isBackLight: true, size: 20 }; console.log(“Is there backlight in the keyboard? ” + keyboard.isBackLight); console.log(“Total keys in the keyboard are ” + keyboard.keys); // keyboard.size = 30 // this is not allowed as all properties of

TypeScript – Conditional Types

TypeScript – Conditional Types ”; Previous Next In TypeScript, conditional types allow you to assign a type to the variables based on the conditions. This enables you to define types that dynamically change based on certain conditions. This feature is very useful for large-scale applications, where you need dynamic typing according to the different situations. Basic Conditional Types We will use the ternary (?:) operator to use the conditional types. It will evaluate the condition, and based on the true or false result, it will select the new type. Syntax You can follow the syntax below to use the conditional types. type A = Type extends anotherType ? TrueType : FalseType; In the above syntax, the ”Type extends anotherType” condition will be evaluated first. If the condition is true, ”type A” will contain the ”TrueType”. Otherwise, it will contain the ”FalseType”. Here, ”extends” keywords check whether ”Type” is the same as ”anotherType” or at least contains all properties of the ”anotherType” type. Example In the code below, we have defined the ”car” type which contains the name, model, and year properties. We have also defined the ”Name” type which contains only ”name” properties. The ”carNameType” type variable stores either a string or any value based on the evaluation result of the ”Car extends Name” condition. Here, the condition will be evaluated as true as the ”Car” type contains all properties of the ”Name” type. After that, we have created the ”carName” variable of ”carNameType” and printed it in the console. type Car = { name: string, model: string, year: number, } type Name = { name: string } // If Car extends Name, then carNameType is string, otherwise it is any type carNameType = Car extends Name ? string : any; // string // Define a variable carName of type carNameType const carName: carNameType = ”Ford”; console.log(carName); // Ford On compiling, it will generate the following JavaScript code. // Define a variable carName of type carNameType const carName = ”Ford”; console.log(carName); // Ford Output Ford Generic Conditional Types Now, let”s learn the generic conditional types. In TypeScript, generic types are similar to the parameters in the function. It allows developers to define a conditional type such that it can be used at multiple places in the code. It provides flexibility to use the different types in the conditional statements. Syntax You can follow the syntax below to use the generic conditional types. type ConditionalType<T> = T extends Type1 ? TrueType : FalseType; In the above syntax, ”conditionalType<T>” has a type ”T” parameter, and ”conditionalType” is the name of the type. The condition ”T extends Type1” checks whether type ”T” extends ”Type1”. If the condition evaluates true, ”TrueType” will be assigned to the ”ConditionalType”. Otherwise, ”FalseType” will be assigned. Example In the code below, ”IsNumArray<T>” is a generic type that takes type ”T” as a parameter. It checks whether the type of the ”T” is an array of numbers (number[]). If yes, it returns ”number”. Otherwise, it returns ”string”. After that, we defined the ”num” and ”str” variables and used the ”IsNumArray” type with them. For the ”num” variable, we have used the ”number[]” parameter, and for the ”str” variable, we have used the ”string[]” parameter. // Generic conditional types type IsNumArray<T> = T extends number[] ? number : string; const num: IsNumArray<number[]> = 5; // number const str: IsNumArray<string[]> = ”5”; // string console.log(num); console.log(str); On compiling, it will generate the following JavaScript code. const num = 5; // number const str = ”5”; // string console.log(num); console.log(str); Output 5 5 Conditional Type Constraints Conditional type constraints are also called type assertions or conditional type predicates. It is used to add constraints on generic types. The generic types are reusable but if you want to reuse them for particular data types like array, number, etc. then you should add constraints with the generic type. Syntax You can follow the syntax below to use the conditional type constraints. type ConditionalType<T extends T1 | T2> = T extends Type1 ? TrueType : FalseType; In the above syntax, we have added the constraints for the type parameter ”T”. It accepts the values of type ”T1” and ”T2”. Example In the code below, ”CondionalType” is a generic type. It takes a number or string type as a value of the type parameter ”T”. The conditional type returns the number if the type of ”T” is a number. Otherwise, it returns a string. Next, we reused the ConditionalType type by passing the number and string as a type parameter. You can notice that when we try to use the ”boolean” as a type parameter, it throws an error. So, it allows to reuse of this generic conditional type with limited types. // Defining the conditional type with constraints type ConditionalType<T extends number | string> = T extends number ? number : string; let x: ConditionalType<number> = 10; let y: ConditionalType<string> = ”Hello”; // let z: ConditionalType<boolean> = true; // Error: Type ”boolean” does not satisfy the constraint ”number | string”. console.log(“The value of x is: “, x); console.log(“The value of y is: “, y); On compiling, it will generate the following JavaScript code. let x = 10; let y = ”Hello”; // let z: ConditionalType<boolean> = true; // Error: Type ”boolean” does not satisfy the constraint ”number | string”. console.log(“The value of x is: “, x); console.log(“The value of y is: “, y); Output The value of x is: 10 The value of y is: Hello Inferring Within Conditional Types In TypeScript, inferring within the conditional types means to infer the types with the conditional type definition. It allows you to create a more flexible type of transformation. For example, if you have an array of elements and match it with the type ”T” in the conditional types. After that, you want to return the type of the array element if the condition becomes true, in such case inferring conditional types is useful. Syntax You can use the ”infer” keyword to

TypeScript – Boxing and Unboxing

TypeScript – Boxing and Unboxing ”; Previous Next A value type in TypeScript is automatically converted into a reference type using a process known as boxing. In other words, boxing refers to transforming a value type into a reference type, and unboxing refers to transforming a reference type into a value type. These are two techniques used in TypeScript to convert a value type to an object type. Boxing is the process of wrapping a value type in an object type. In contrast, unboxing is the process of unwrapping an object type back to a value type. The two techniques improve code performance by reducing the amount of memory allocated each time a value type is cast to an object type. Boxing and Unboxing in TypeScript refer to the way primitive values are handled when they are passed to or returned from functions. When a primitive value is passed to a function, it is boxed, meaning it is converted to an object. When the value is returned from the function, the object is unboxed, and the primitive value is returned. This process is necessary because primitive values are not object-oriented and must be converted for a function to manipulate them. Boxing and unboxing can improve performance and memory usage in TypeScript applications. Let us explain both topics one by one in detail. Boxing in TypeScript Boxing in TypeScript refers to converting a value of a primitive data type (e.g., number, string, boolean) into an object of the corresponding wrapper class. TypeScript has built-in wrapper classes for the primitive data types, such as Number, String, and Boolean. These wrapper classes provide useful methods and properties that can be used to manipulate the corresponding primitive data types. For example, the Number wrapper class has methods such as toFixed(), toString(), and valueOf(). Boxing is an important concept in TypeScript, as it allows for using methods on primitive data types that would not otherwise be available. Syntax let variable_name: number = 12345 let boxing_variable_name: Object = variable_name // Boxing In the above syntax, we can see the value of variable_name variable of type number is converted to an object type variable in the process of boxing. Example In this example, we perform a boxing operation. We declare a class named BoxingClass and declare two variables. One is the number, and the other is an object-type variable. We declare a method named boxingMethod(), where we perform the boxing operations. And finally, we console log the my_object variable’s value. class BoxingClass { my_number: number = 123 my_object: Object boxingMethod() { this.my_object = this.my_number console.log(”Boxing Occurs for my_object variable”) } } let boxing_object = new BoxingClass() boxing_object.boxingMethod() console.log(”my_object value: ”, boxing_object.my_object) On compiling, it will generate the following JavaScript code − var BoxingClass = /** @class */ (function () { function BoxingClass() { this.my_number = 123; } BoxingClass.prototype.boxingMethod = function () { this.my_object = this.my_number; console.log(”Boxing Occurs for my_object variable”); }; return BoxingClass; }()); var boxing_object = new BoxingClass(); boxing_object.boxingMethod(); console.log(”my_object value: ”, boxing_object.my_object); Output The above code will produce the following output − Boxing Occurs for my_object variable my_object value: 123 Unboxing in TypeScript Unboxing in TypeScript converts a value with a compound data type (object, array, tuple, union, etc.) into a simpler data type (string, number, boolean, etc.). It is similar to “unboxing” in other programming languages, where a value of a particular type (like an object) is converted into a simpler type, such as a string or number. In TypeScript, unboxing is done using the type assertion syntax (angle brackets) to specify the type of the value to be unboxed. For example, if we have a value of type any, we can unbox it to a number type by using the following syntax: <number> value. Syntax let variable_name: number = 12345 let boxing_variable_name: Object = variable_name // Boxing let unboxing_variable_name: number = <number>boxing_variable_name // Unboxing In the above syntax, we can see the value of variable_name variable of type number is converted to an object type variable in the process of boxing and then converted back to a number using unboxing. Example In this example, we perform both boxing and unboxing operations. We declare a class named BoxingUnboxingClass and declare three variables: two are the number, and another is an object type variable. Firstly, we perform the boxing process using the boxingMethod(), and then we perform the unboxing using the unboxingMethod(). And finally, we console log the variable’s value. class BoxingUnboxingClass { my_number: number = 123 boxing_variable: Object unboxing_variable: number boxingMethod() { this.boxing_variable = this.my_number console.log(”Boxing Occurs!”) } unboxingMethod() { this.unboxing_variable = <number>this.boxing_variable console.log(”Unboxing Occurs!”) } } let boxing_unboxing_object = new BoxingUnboxingClass() boxing_unboxing_object.boxingMethod() boxing_unboxing_object.unboxingMethod() console.log(”boxing_variable value: ”, boxing_unboxing_object.boxing_variable) console.log( ”unboxing_variable value: ”, boxing_unboxing_object.unboxing_variable ) On compiling, it will generate the following JavaScript code − var BoxingUnboxingClass = /** @class */ (function () { function BoxingUnboxingClass() { this.my_number = 123; } BoxingUnboxingClass.prototype.boxingMethod = function () { this.boxing_variable = this.my_number; console.log(”Boxing Occurs!”); }; BoxingUnboxingClass.prototype.unboxingMethod = function () { this.unboxing_variable = this.boxing_variable; console.log(”Unboxing Occurs!”); }; return BoxingUnboxingClass; }()); var boxing_unboxing_object = new BoxingUnboxingClass(); boxing_unboxing_object.boxingMethod(); boxing_unboxing_object.unboxingMethod(); console.log(”boxing_variable value: ”, boxing_unboxing_object.boxing_variable); console.log(”unboxing_variable value: ”, boxing_unboxing_object.unboxing_variable); Output The above code will produce the following output − Boxing Occurs! Unboxing Occurs! boxing_variable value: 123 unboxing_variable value: 123 The boxing and unboxing in TypeScript refer to the way primitive values are handled when they are passed to or returned from functions. Boxing converts a primitive value type into an object type, while unboxing is the reverse process of converting an object type back into a primitive value type. These techniques improve code performance by reducing the amount of memory allocated each time a value type is cast to an object type. In TypeScript, boxing is done by assigning a primitive value to an object variable, and unboxing is done using type assertion syntax (angle brackets) to specify the type of the value to be unboxed. It is important to note that the primitive value”s memory is allocated on the stack, and the object value”s memory is allocated on

TypeScript – If Statement

TypeScript – If Statement ”; Previous Next In TypeScript, the if statement evaluates a condition (a boolean expression) and executes a block of code only if the condition is true. The condition is evaluated before the block of code block is executed. If the condition is false, the code block following the else (if present) is executed. We will discuss the if…else statement in more detail in the next chapter. Syntax To write an if statement syntax, we use the if keyword followed by a condition in parentheses and then a block of code enclosed in curly braces ({}). if(boolean_expression) { // statement(s) will execute if the boolean expression is true } If the Boolean expression evaluates to true, then the block of code inside the if statement will be executed. If the Boolean expression evaluates to false, then the first set of code after the end of the if statement (after the closing curly brace) will be executed. Flowchart The following flow chart shows how the if statement works. Examples Let”s understand the if statement in details with the help of some examples in TypeScript. Example 1 In the example below, we define a variable num of number type and assign it the value 5. Since the condition evaluates to true and the code of the if statement is executed. var num: number = 5 if (num > 0) { console.log(“number is positive”) } On compiling, it will generate following JavaScript code. var num = 5; if (num > 0) { console.log(“number is positive”); } The above example will print “number is positive” as the condition specified by the if block is true. number is positive Example 2 In the example below, the condition is a boolean variable isQualified. If isQualified is true, the if statement executes the block of code following it. var isQualified: boolean = true; if( isQualified ) { console.log(“Qualified for driving”); } On compiling, it will generate the following JavaScript code. var isQualified = true; if( isQualified ) { console.log(“Qualified for driving”); } The above example will print “Qualified for driving” as the condition specified by the if block is true. Qualified for driving Example 3 In the example below, we define variables x, and y of number type and assign values 20 & 30 to them. The condition of the if statement is x < y. With these given values, the condition evaluates to true, so the code within the if statement is executed. var x: number = 20; var y: number = 30; if (x < y){ console.log(“x is less than y”); } On compiling, it will produce the following JavaScript code. var x = 20; var y = 30; if (x < y){ console.log(“x is less than y”); } The above example will print “x is less than y” as the condition (20 < 30) specified by the if statement is true. x is less than y Example 4: When condition is false var x: number = 100; var count: number = 0; if (x < 100){ count++; } console.log(count); On compiling, it will produce the following JavaScript code. var x = 100; var count = 0; if (x < 100){ count++; } console.log(count); Since the condition (x < 100) evaluates to false, the if block will not be executed. The value of count will remain same as previous. The output is as follows – 0 Print Page Previous Next Advertisements ”;

TypeScript – Triple-Slash Directives

TypeScript – Triple-Slash Directives ”; Previous Next Triple-slash directives are similar to single-line comments which contain a single XML tag. They are used to provide instructions to the TypeScript compiler about processing the TypeScript file. Triple-slash directives start with three forward slashes (///) and are mainly placed at the top of the code file. Triple-slash directives are mostly used in TypeScript. However, they can also be used with JavaScript projects that use TypeScript. In TypeScript, you can use triple-slash directives for two purposes. Reference Directives Reference directives are mainly used to tell the compiler to include another TypeScript file in the compilation process. They specify the dependencies between multiple files. Furthermore, they are also used to declare dependency packages and include libraries in the TypeScript file. Syntax /// <reference path=”file_path” /> In the above syntax, we have used three forward slashes first to define the triple-slash directives. After that, we used the XML tag <reference /> and added a path attribute to it. The path attribute takes the file path as a value. Similarly, you can also use other XML tags with three forward slashes. Types of Triple-Slash Reference Directives Here are the most commonly used triple-slash reference directives in a JavaScript/TypeScript environment: ///<reference path=”…” /> − It is used to add a reference of one TypeScript file in another file. ///<reference types=”…” /> − It is used to declare a dependency on a package. ///<reference lib=”…” /> − It is used to include a library file that is part of the compilation context. Example: Referencing File Paths The main purpose of the triple-slash directives is to reference other files in particular TypeScript files. Filename: MathFunctions.ts In the below code, we have defined the add() function that takes two numbers as a parameter and returns the sum of them. We also export that function using the export keyword to use it in a different file. // This file will be referenced in app.ts export function add(a: number, b: number): number { return a + b; } Filename: app.ts In this file, we have imported the add() function from the mathFunctions file. We have also used the reference directive in this file to tell the file path to the compiler. /// <reference path=”mathFunctions.ts” /> import { add } from ”./mathFunctions”; console.log(”Addition of 10 and 20 is:”, add(10, 20)); Output Addition of 10 and 20 is 30 Example: Referencing Type Definition The triple-slash directives can also be used to specify the reference type definition for the external module. You can use the <reference type=”module_type” /> directive to specify the type of the module. App.ts In the code below, we have imported the ‘fs’ module. Before that, we have used the triple-slash directive to specify the type of the module. Next, we used the readFileSync() method of the ‘fs’ module to read the file content. /// <reference types=”node” /> import * as fs from ”fs”; const content = fs.readFileSync(”sample.txt”, ”utf8”); console.log(”File content:”, content); Sample.txt The below file contains plain text. Hello, this is a sample text file. Output File content: Hello, this is a sample text file. Example: Including Libraries When you want to use a specific library during the TypeScript compilation, you can use the ///<reference lib=”lib_name” /> triple-slash directive to specify it. In the code below, we have used the triple-slash directive to specify the “es2015.array” library. /// <reference lib=”es2015.array” /> const str = [“Hello”, “1”, “World”, “2”]; const includesTwo = str.includes(“2″); console.log(includesTwo); Output true Module System Directives Module system directives are used to specify how modules are loaded in the TypeScript file. They are used to load modules asynchronously. There are two types of module system directives in TypeScript: ///<amd-module name=”…” />: It is used to specify the module name for loading. ///<amd-dependency path=”…” />: It is used to specify the path for the dependencies of the AMD module. Example In the code below, we have used the AMD-module triple-slash directive which specifies to load the ‘MyModule’ module asynchronously. /// <amd-module name=”MyModule” /> export function displayMessage() { return “Hello from MyModule”; } Triple-slash directives allow developers to enhance JavaScript projects by providing advanced compilation options, module loading, and integration with various types and libraries. Print Page Previous Next Advertisements ”;

TypeScript – Ambients

TypeScript – Ambients ”; Previous Next Ambient declarations are a way of telling the TypeScript compiler that the actual source code exists elsewhere. When you are consuming a bunch of third party js libraries like jquery/angularjs/nodejs you can’t rewrite it in TypeScript. Ensuring typesafety and intellisense while using these libraries will be challenging for a TypeScript programmer. Ambient declarations help to seamlessly integrate other js libraries into TypeScript. Defining Ambients Ambient declarations are by convention kept in a type declaration file with following extension (d.ts) Sample.d.ts The above file will not be transcompiled to JavaScript. It will be used for type safety and intellisense. The syntax for declaring ambient variables or modules will be as following − Syntax declare module Module_Name { } The ambient files should be referenced in the client TypeScript file as shown − /// <reference path = ” Sample.d.ts” /> Example Let’s understand this with help of an example. Assume you been given a third party javascript library which contains code similar to this. FileName: CalcThirdPartyJsLib.js var TutorialPoint; (function (TutorialPoint) { var Calc = (function () { function Calc() { } Calc.prototype.doSum = function (limit) { var sum = 0; for (var i = 0; i <= limit; i++) { Calc.prototype.doSum = function (limit) { var sum = 0; for (var i = 0; i <= limit; i++) { sum = sum + i; return sum; return Calc; TutorialPoint.Calc = Calc; })(TutorialPoint || (TutorialPoint = {})); var test = new TutorialPoint.Calc(); } } } } } As a typescript programmer you will not have time to rewrite this library to typescript. But still you need to use the doSum() method with type safety. What you could do is ambient declaration file. Let us create an ambient declaration file Calc.d.ts FileName: Calc.d.ts declare module TutorialPoint { export class Calc { doSum(limit:number) : number; } } Ambient files will not contain the implementations, it is just type declarations. Declarations now need to be included in the typescript file as follows. FileName : CalcTest.ts /// <reference path = “Calc.d.ts” /> var obj = new TutorialPoint.Calc(); obj.doSum(“Hello”); // compiler error console.log(obj.doSum(10)); The following line of code will show a compiler error. This is because in the declaration file we specified the input parameter will be number. obj.doSum(“Hello”); Comment the above line and compile the program using the following syntax − tsc CalcTest.ts On compiling, it will generate following JavaScript code(CalcTest.js). //Generated by typescript 1.8.10 /// <reference path = “Calc.d.ts” /> var obj = new TutorialPoint.Calc(); // obj.doSum(“Hello”); console.log(obj.doSum(10)); In order to execute the code, let us add an html page with script tags as given below. Add the compiled CalcTest.js file and the third party library file CalcThirdPartyJsLib.js. <html> <body style = “font-size:30px;”> <h1>Ambient Test</h1> <h2>Calc Test</h2> </body> <script src = “CalcThirdPartyJsLib.js”></script> <script src = “CalcTest.js”></script> </html> It will display the following page − On the console, you can see the following output − 55 Similarly, you can integrate jquery.d.ts or angular.d.ts into a project, based on your requirement. Print Page Previous Next Advertisements ”;