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 ”;
Category: typescript
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 ”; 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 ”;
TypeScript – Mixins
TypeScript – Mixins ”; Previous Next TypeScript is an Object-oriented programming language and contains the classes, which is a blueprint for the object. The class can be defined as shown below in TypeScript. class MathOps { // defining a method add(a: number, b: number): void { console.log(”sum is: ”, a + b); } } Now, suppose we have multiple classes like the above which contain different operations. What if you want to reuse both classes and want to create a third class by extending both classes? For example, if you try to extend the ”allOps” class with ”MathOps1”, and ”BitwiseOps” classes, TypeScript will give you an error as multiple inheritance is not allowed in TypeScript. class allOps extends MathOps, BitwiseOps { // Executable code } To solve the above problem, developers can use the mixins in TypeScript. Introduction to Mixins In TypeScript, mixins is a concept that allows us to extend a single class via multiple classes. This way, we can reuse the class components and combine their methods and properties in a single class. We can use the declaration merging technique to extend the single class via multiple classes. Declaration Merging When you have two declarations of the same name, it will be merged without throwing any error. For example, in the below code, we have defined the interface ”A” twice containing different properties. After that, we have created the ”obj” object of type ”A”, which contains the properties ”a” and ”b” as both interfaces ”A” are merged. // Definition of an interface with the same name twice interface A { a: string; } interface A { b: string; } // Object that implements the interface let obj: A = { a: ”a”, b: ”b” }; console.log(obj.a); // a console.log(obj.b); // b On compiling, it will generate the following TypeScript code. // Object that implements the interface let obj = { a: ”a”, b: ”b” }; console.log(obj.a); // a console.log(obj.b); // b Output The output of the above example is as follows – a b Now, let”s understand how we can use the declaration merging technique to extend multiple classes with a single class. Implementing Our Mixin Helper Function Let”s understand the below example code line-by-line. We have defined the ”swimmer” class, which contains the StartSwim() and EndSwim() methods. Next, we have defined the Cyclist class, which contains startCycle() and endCycle() methods. Next, the ”combineMixins()” function is a helper function that allows us to mix the properties and methods of two or more classes in one class. That”s why it is called mixin function. The function takes the derived or parent class as a first parameter, and the array of base or child classes as a second parameter. It iterates through the array of base classes using the forEach() method. In the forEach() method callback, it iterates through each property of the single base class and adds in the prototype of the derived class using the defineProperty() method. After that, we have defined the ”Biathlete” class. The interface ”Biathlete” extends the ”Swimmer” and ”Cyclist” classes to merge all property and method declarations of both classes into the ”Biathlete” class. However, it won”t combine the implementation of methods. Next, we call the ”combineMixins()” function which merges the implementations of methods of the classes in other classes. Next, we created the instance of the ”Biathlete” class and used it to call the methods of the ”Swimmer” and ”Cyclist” classes. // Swimmer class definition class Swimmer { // Methods StartSwim() { console.log(”Starting the swimming session…”); } EndSwim() { console.log(”Completed the swimming session.”); } } // Cyclist class definition class Cyclist { // Methods StartCycle() { console.log(”Starting the cycling session…”); } EndCycle() { console.log(”Completed the cycling session.”); } } // export class Biathlete extends Swimmer, Cyclist{} function combineMixins(derived: any, bases: any[]) { // Iterate over the base classes bases.forEach(base => { // Iterate over the properties of the base class Object.getOwnPropertyNames(base.prototype).forEach(name => { // Copy the properties of the base class to the derived class Object.defineProperty(derived.prototype, name, Object.getOwnPropertyDescriptor(base.prototype, name)); }); }); } // Export Biathlete class export class Biathlete { } // Use interface to combine mixins export interface Biathlete extends Swimmer, Cyclist { } // Combine mixins combineMixins(Biathlete, [Swimmer, Cyclist]); // Create an instance of Biathlete class const athlete = new Biathlete(); // Call the methods athlete.StartSwim(); athlete.EndSwim(); athlete.StartCycle(); athlete.EndCycle(); Output Starting the swimming session… Completed the swimming session. Starting the cycling session… Completed the cycling session. This way, we can merge the structure of two components using the interface. After that, we can use the mixins function to combine the implementations of two components into the third one and reuse them. Print Page Previous Next Advertisements ”;
TypeScript – Symbols
TypeScript – Symbols ”; Previous Next In TypeScript, a symbol is a primitive data type that is unique and immutable. The symbols are introduced in ECMAScript 2015 (also known as ES6). As we use the number, string, or boolean to create the variables of different data-type, we can use the symbol type to create the Symbol. Using the symbol types has many benefits as it provides more features than other data types. In this tutorial, we will learn about the basics of the Symbol and its different uses of the Symbol. Syntax Symbols in TypeScript are created using the Symbol() constructor function – let test_symbol = Symbol(); You can pass a key as a symbol parameter to identify the Symbol. let key_symbol = Symbol(“key-for-symbol”); Symbols are unique and immutable In TypeScript, you can create multiple symbols that are unique. Even if you create the symbols with the same keys, they will be unique. Let”s create two different symbols with the same key. let first_sym = Symbol(“sym”); let second_sym = Symbol(“sym”); console.log(first_sym === second_sym); The above TypeScript code show that both symbols are unique and not comparable. On compiling, it will generate the same code in JavaScript. The output is as follows – false Symbols as keys for object properties Symbols can also be used as keys for object properties just like strings. In the example below, we have created the symbol and defined the object. We used the obj_symbol as a property of the object. Also, we can access it like the object”s normal property. const obj_symbol = Symbol(); // creating the object let object = { // using the obj_symbol as key of object [obj_symbol]: “obj value”, }; // accessing the symbol property of the object console.log( “The value of the obj_symbol property in the object is ” + object[obj_symbol] ); On compiling, it will generate the same code in JavaScript. It will produce the following output − The value of the obj_symbol property in the object is obj value Symbol with the switch case statement As every symbol is unique, we can use it as a case of the switch-case statement. When we use the symbols with the switch case statement, it ensures that every case is unique. If any case doesn’t match with the case passed as a parameter of the switch statement, it goes to the default case. switch(symbol) { case symbol1: break case symbol2: break; } In the above syntax, a symbol is passed as a parameter of the switch statement. After that, we used the symbol name followed by the case keyword to create a different case. Example In the example below, we have created four different symbols. After that, we defined the print_symbol function, which contains the switch case statement to handle the different cases. In the switch case statement, we are using the symbol values as a case and executing the code of the particular case. // different symbols const symbol1 = Symbol(); const symbol2 = Symbol(); const symbol3 = Symbol(); const symbol4 = Symbol(); function print_symbol(symbol) { // creating the switch case statement switch (symbol) { // different cases case symbol1: console.log(“The case is symbol 1.”); break; case symbol2: console.log(“The case is symbol 2.”); break; case symbol3: console.log(“The case is symbol 3.”); debugger; break; case symbol4: console.log(“The case is symbol 4.”); break; default: console.log(“The case is default.”); } } // calling the function print_symbol(symbol2); print_symbol(symbol4); On compiling, it will generate the same code in JavaScript. It will produce the following output − The case is symbol 2. The case is symbol 4. Unique Symbols In TypeScript, Symbol is a primitive data type. So, we need to use it as a type only, but we can also use it as literals using the ‘unique symbol’. The symbol includes the unique symbol, which means the unique symbol is a subtype of the symbol. We can use the unique symbol with only const variables and readonly properties. If we want to reference the specific symbol type to another variable, we can use the ‘typeof’ operator. Syntax You can follow the syntax below to use the symbol as a literal using the unique symbol. const test_symbol: unique symbol = Symbol(); let symbol1: typeof test_symbol = test_symbol; class C { static readonly symb: unique symbol = Symbol(“unique symbol”); } Example In the example below, we have declared the test_symbol of the type symbol and used the unique symbol keyword to use the symbol as a type literal. Also, users can observe how we can use the typeof operator to use the symbol as a type literal of the variables declared with the let and var keywords. Also, we have used the unique symbol keyword to define the type of the readonly static class’s member. // here, we used the unique symbol to define the type of the sym1. const test_symbol: unique symbol = Symbol(); // we can”t reference the unique symbol to the let type of variable // let sym2: unique symbol = Symbol(); // to reference the symbol type to the variables declared with the let keyword, using the typeof operator. let symbol1: typeof test_symbol = test_symbol; console.log(“The value of symbol1 is ” + typeof test_symbol); // referencing the unique symbol to the static class property class C { static readonly symb: unique symbol = Symbol(“unique symbol”); } On compiling, it will generate the following JavaScript code − // here, we used the unique symbol to define the type of the sym1. var test_symbol = Symbol(); // we can”t reference the unique symbol to the let type of variable // let sym2: unique symbol = Symbol(); // to reference the symbol type to the variables declared with the let keyword, using the typeof operator. var symbol1 = test_symbol; console.log(“The value of symbol1 is ” + typeof test_symbol); // referencing the unique symbol to the static class property var C = /** @class */ (function () { function C() { } C.symb = Symbol(“unique symbol”); return C; }()); The above code will
TypeScript – tsconfig.json
TypeScript – tsconfig.json ”; Previous Next The TypeScript tsconfig.json file is a configuration file to specify the compiler options. These compiler options are used to compile the TypeScript code and convert it into JavaScript code. However, it also allows developers to specify some more configurations in the JSON format to use in the project. The tsconfig.json file is always present in the root directory of the project. This file contains the data in JSON format. Basic Structure of tsconfig.json file The tsconfig.json file mainly contains 5 properties given below and all are optional: compileOnSave compilerOptions files include exclude If you don’t use any of these properties in the tsconfig.json file, the compiler uses the default settings. Here is the basic structure of the tsconfig.json file. { “compileOnSave”: true, “compilerOptions”: { “target”: “es6”, “lib”: [ “es6”, “dom” ], “module”: “commonjs” }, “files”: [ “app.ts”, “base.ts” ], “include”: [ “src/**/*” ], “exclude”: [ “node_modules”, “src/**/*.calc.ts” ] } In the above file, you can add more compiler options, or elements in the list of other properties according to the requirements. Let’s understand each property one by one here. The compileOnSave Property The compilerOnSave property is used to specify whether you want to compile the project code immediately when you save the code. The default value of the compilerOnSave property is false. If you use the false value for this property, you need to compile the code manually. Here is how you can use the compileOnSave property in the tsconfig.json file. { “compileOnSave”: boolean_value } The compilerOptions Property The compilerOptions is a widely used property in the tsconfig.json file. It is used to specify the settings for the TypeScript compiler to compile the code. For example, if you want to use a specific version of JavaScript or a module while compiling the TypeScript code, you can modify the compilerOptions property. Here are some common compiler options to use in the tsconfig.json file. Option Description target Specifies the target ECMAScript version for the output JavaScript files. “es6” targets ECMAScript 2015. experimentalDecorators Enables experimental support for ES decorators, which are a stage 2 proposal to the ECMAScript standard. lib Specifies a list of library files to be included in the compilation. For example, including “es6” and “dom” for relevant APIs. module Specifies the module system for the project. “commonjs” is typically used for Node.js projects. esModuleInterop Enables compatibility with non-ES Module compliant imports, allowing default imports from modules with no default export. resolveJsonModule Allows importing of .json files as modules in the project. strict Enables all strict type-checking options, improving the strictness and accuracy of type checks in TypeScript. listFiles When set, the compiler will print out a list of files that are part of the compilation. outDir Redirects output structure to the directory specified. Useful for placing compiled files in a specific directory. outFile Concatenates and emits output to a single file. If outFile is specified, outDir is ignored. rootDir Specifies the root directory of input files. Useful for controlling the output directory structure with outDir. sourceRoot Specifies the location where the compiler should look for TypeScript files instead of the default location. allowJs Allows JavaScript files to be compiled along with TypeScript files. Useful in projects that mix JS and TS. strictNullChecks When enabled, the compiler will perform strict null checks on your code, which can help prevent null or undefined access errors. Here is the common way to use the compilerOptions in tsconfig.json file. { “compilerOptions”: { “target”: “es6”, “lib”: [ “es6”, “dom” ], “module”: “commonjs” } } The files Property The files property takes the list of files as a value to include in the compilation process. You can add filenames directly if it is in the root directory, or the relative or absolute file path for each file, which you want to include in the compilation process. Here, we have shown how to use files properties in the tsconfig.json file. “files”: [ “app.ts”, “base.ts” ] The include Property The include property allows developers to add the list of TypeScript files for the compilation using the wildcard queries. If you want to add all files in the compilation, you can use the below wildcard query. “include”: [ “src/**/*” ] The above configuration adds all files, which are in the src directory. The exclude Property The exclude property is the opposite of the include property. It allows developers to remove particular files using the wildcard queries from the compilation process. “exclude”: [ “node_modules”, “src/**/*.calc.ts” ] The above configuration removes the node modules and calc.ts file from the compilation process. Common Scenarios and Configurations Here, we have explained the common scenarios for which developers are required to change the tsconfig.json file. Targeting Different ECMAScript Versions If you want to target different ECMAScript versions while compiling the TypeScript code, you can use the below configurations. Here, we have changed the value of the target and module properties of the compilerOptions object. { “compilerOptions”: { “target”: “es6”, “module”: “es2015” } } Including Node.js Type Definitions When you work with Node.js, you might need to add a type definition, and here is how you can add it. { “compilerOptions”: { “module”: “commonjs”, “target”: “es2018”, “lib”: [“es2018”, “dom”] }, “include”: [ “src/**/*” ] } Excluding Test Files Sometimes, developers are required to remove the testing files from the compilation process. Here is how you can remove particular test files or directories using the exclude property. { “exclude”: [“**/*.spec.ts”, “**/*.test.ts”] } It is always important for TypeScript developers to understand managing the tsconfig.json file. You can edit this file to change the module while compiling the code, adding and removing files from the compilation process, and for automatic compilation after saving the file. Print Page Previous Next Advertisements ”;
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+” 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 ”;