TypeScript – Parameter Destructuring

TypeScript – Parameter Destructuring ”; Previous Next In TypeScript, parameter destructuring is unpacking the argument object into separate parameter variables. For example, suppose we have passed the object with multiple properties as an argument of any function. In that case, we can destructure the object in the parameter and access all required properties of the object in a separate variable. However, we can destructure the object properties or array passed as an argument of the function. Also, we have to define the type of every parameter using type annotation in TypeScript while destructuring the parameters. So it might not be very clear for beginners. Syntax You can follow the syntax below for parameter destructuring in TypeScript. function getObjValues({ key1, key2 }: { key1: string; key2: number }) { // use key1 and key2 as a variable } // calling the function with an object getObjValues({ key1: “Hello”, key2: 20 }); In the above syntax, we have passed the argument as a function. Users can see how we have destructured every object value in the parameter. Examples Now, we will look at the various examples of parameter destructuring and learn different uses of it. Example 1 In the example below, we have created the printObjValues() function, which takes an object as a parameter. We are destructuring the object and storing the key values of the object in the parameter variables. Also, users can see how we have used the parameter values in the function. function printObjValues({ key1, key2 }: { key1: string; key2: number }) { console.log(“The value of key1 is ” + key1); console.log(“The value of key2 is ” + key2); } printObjValues({ key1: “Hello”, key2: 20 }); printObjValues({ key1: “TypeScript”, key2: 50 }); On compiling, it will generate the following JavaScript code − function printObjValues(_a) { var key1 = _a.key1, key2 = _a.key2; console.log(“The value of key1 is ” + key1); console.log(“The value of key2 is ” + key2); } printObjValues({ key1: “Hello”, key2: 20 }); printObjValues({ key1: “TypeScript”, key2: 50 }); The above code will produce the following output − The value of key1 is Hello The value of key2 is 20 The value of key1 is TypeScript The value of key2 is 50 Example 2 In the example below, we are destructuring the object values in the parameter variable, but we have also assigned the default values to the parameter variables. The default values of the param2 are “default”. So, if we don’t pass the param2 key-values pair in the argument object, it will use the default value, and the code will execute without any error. Also, users can see that we have used the ‘?’ to make the param2 parameter optional. function getParams({ param1, param2 = “default”, }: { param1: boolean; param2?: string; }) { console.log(“The value of param1 is ” + param1); console.log(“The value of param2 is ” + param2); } getParams({ param1: true, param2: “value” }); getParams({ param1: false }); On compiling, it will generate the following JavaScript code − function getParams(_a) { var param1 = _a.param1, _b = _a.param2, param2 = _b === void 0 ? “default” : _b; console.log(“The value of param1 is ” + param1); console.log(“The value of param2 is ” + param2); } getParams({ param1: true, param2: “value” }); getParams({ param1: false }); The above code will produce the following output − The value of param1 is true The value of param2 is value The value of param1 is false The value of param2 is default Example 3 In this example, all parameters are optional. We have assigned the default object containing all keys and default values to the parameter variables. So, we can use the argument object with one, two, three, or no key-value pairs. Users can observe that we have invoked the function by passing the object containing various numbers of key-values pairs as an argument. // Creating the function whose all parameters are optional and initializing them with default values. function sample_function( { value1, value2, value3, }: { value1?: number; value2?: number; value3?: number; } = { value1: 20, value2: 30, value3: 40 } ): number { let sum = value1 + value2 + value3; return sum; } console.log(“The sum of default values is ” + sample_function()); console.log( “The sum of 10000, 20302, and value3 is ” + sample_function({ value1: 10000, value2: 20302 }) ); console.log( “The sum of 10, 20, and 25 is ” + sample_function({ value1: 10, value2: 20, value3: 25 }) ); On compiling, it will generate the following JavaScript code − // Creating the function whose all parameters are optional and initializing them with default values. function sample_function(_a) { var _b = _a === void 0 ? { value1: 20, value2: 30, value3: 40 } : _a, value1 = _b.value1, value2 = _b.value2, value3 = _b.value3; var sum = value1 + value2 + value3; return sum; } console.log(“The sum of default values is ” + sample_function()); console.log(“The sum of 10000, 20302, and value3 is ” + sample_function({ value1: 10000, value2: 20302 })); console.log(“The sum of 10, 20, and 25 is ” + sample_function({ value1: 10, value2: 20, value3: 25 })); The above code will produce the following output − The sum of default values is 90 The sum of 10000, 20302, and value3 is NaN The sum of 10, 20, and 25 is 55 Example 4 In this example, we are passing the object of lock type as a function parameter. The lock interface contains the lock_id and isDurable properties. We created the ‘lockObj’ and passed it as an argument of the callLockFunc() function. In the callLockFunc() function, we have destructured the parameter object in the variables and print them to show its values. interface lock { lock_id?: string; isDurable?: boolean; } let lockObj: lock = { lock_id: “4523fdr0”, isDurable: true, }; function callLockFunc(obj: lock) { let { lock_id, isDurable } = obj; console.log(“The destructured lock_id value is ” + lock_id); console.log(“The destructured isDurable value is ” + isDurable); } callLockFunc(lockObj); lockObj.isDurable = false; lockObj.lock_id = “eredf”; callLockFunc(lockObj); On

TypeScript – Objects

TypeScript – Objects ”; Previous Next An object in TypeScript is an instance which contains set of key value pairs. The key value pairs are also referred as object properties. The values can be scalar values or functions or even array of other objects. If a property”s value is a function, that property is known as method. Syntax The syntax to create an object in TypeScript is given below − var object_name = { key1: “value1”, //scalar value key2: “value”, key3: function() { //functions }, key4:[ “content1”, “content2”] //collection }; As shown above, an object can contain scalar values, functions and structures like arrays and tuples. Type Annotations In TypeScript, we should annotate the object properties as follows – let person: {name: string, age: number} = { name: “Tom Hanks”, age: 35, } In the above example we annotated the properties name and age of the person object. We can also use interface to create type for object properties. Look the below example – interface PersonType { fullname: string; age: number } var person: PersonType = { fullname:”Tom Hanks”, age:32 }; Object Literal Notation The object literal notation is the easiest way to create an object in TypeScript. We use curly braces ({}) to create object. Each property of the object is separated by a comma. Each property is written as property name (key) followed by colon (:) followed by property value. Example In the example below, we have created an object named person containing two properties. The first property is firstname: “Tom” and the second property is lastname: “Hanks”. We access the property values and print them in console. var person:{ firstName: string, lastName: string}= { firstName:”Tom”, lastName:”Hanks” }; //access the object values console.log(person.firstName) console.log(person.lastName) On compiling, it will generate the following code in JavaScript. var person = { firstName: “Tom”, lastName: “Hanks” }; //access the object values console.log(person.firstName); console.log(person.lastName); Output Tom Hanks TypeScript Type Template Let”s say you created an object literal in JavaScript as − var person = { firstname:”Tom”, lastname:”Hanks” }; In case you want to add some value to an object, JavaScript allows you to make the necessary modification. Suppose we need to add a function to the person object later this is the way you can do this. person.sayHello = function(){ return “hello”;} If you use the same code in Typescript the compiler gives an error. This is because in Typescript, concrete objects should have a type template. Objects in Typescript must be an instance of a particular type. You can solve this by using a method template in declaration. Example: Typescript Type template var person = { firstName:”Tom”, lastName:”Hanks”, sayHello:function() { } //Type template } person.sayHello = function() { console.log(“hello “+person.firstName) } person.sayHello() On compiling, it will generate the same code in JavaScript. Output The above generated JavaScript code will produce the following output – hello Tom Objects as Function Parameters Objects can also be passed as parameters to function. Example: Objects as function parameters var person = { firstname:”Tom”, lastname:”Hanks” }; var invokeperson = function(obj: { firstname:string, lastname :string }) { console.log(“first name :”+obj.firstname) console.log(“last name :”+obj.lastname) } invokeperson(person) The example declares an object literal. The function expression is invoked passing person object. On compiling, it will generate following JavaScript code. //Generated by typescript 1.8.10 var person = { firstname: “Tom”, lastname: “Hanks” }; var invokeperson = function (obj) { console.log(“first name :” + obj.firstname); console.log(“last name :” + obj.lastname); }; invokeperson(person); Output first name :Tom last name :Hanks Anonymous Objects You can create and pass an anonymous object on the fly. Example: Anonymous Object var invokeperson = function(obj:{ firstname:string, lastname :string}) { console.log(“first name :”+obj.firstname) console.log(“last name :”+obj.lastname) } invokeperson({firstname:”Sachin”,lastname:”Tendulkar”}); On compiling, it will generate following JavaScript code. //Generated by typescript 1.8.10 var invokeperson = function (obj) { console.log(“first name :” + obj.firstname); console.log(“last name :” + obj.lastname); }; invokeperson({ firstname: “Sachin”, lastname: “Tendulkar” }); Output first name :Sachin last name :Tendulkar Duck-typing In duck-typing, two objects are considered to be of the same type if both share the same set of properties. Duck-typing verifies the presence of certain properties in the objects, rather than their actual type, to check their suitability. The concept is generally explained by the following phrase − “When I see a bird that walks like a duck and swims like a duck and quacks like a duck, I call that bird a duck.” The TypeScript compiler implements the duck-typing system that allows object creation on the fly while keeping type safety. The following example shows how we can pass objects that don’t explicitly implement an interface but contain all of the required members to a function. Example interface IPoint { x:number y:number } function addPoints(p1:IPoint,p2:IPoint):IPoint { var x = p1.x + p2.x var y = p1.y + p2.y return {x:x, y:y} } //Valid var newPoint = addPoints({x:3,y:4},{x:5,y:1}) //Error var newPoint2 = addPoints({x:1},{x:4,y:3}) Print Page Previous Next Advertisements ”;

TypeScript – Static Methods and Properties

TypeScript – Static Methods and Properties ”; Previous Next In TypeScript, static properties belong to the class itself, instead of the instances of the class. The static methods and properties can be accessed without using the instance of the classes. This means you do not need to create an object of the class to use these methods and properties. There are two types of properties and methods in TypeScript. One is instance properties and methods and another one is static properties and methods. Here, you will learn about static properties and methods. Static properties and methods are useful to create utility functions and constants that don”t change across different instances. For example, if you are creating the circle class, and want to define the ”PI” property inside the class, you can make it static as it is a constant. Static Properties We can use the ”static” keyword before the property name to define static properties. Syntax You can follow the syntax below to define the static properties in TypeScript classes. class className { static property_name: data_type = value; } In the above syntax, we have used the ”static” keyword before the property name to define the static property. To access the static property, we can use the class name followed by a dot followed by the static property name as shown below. className.property_name; Example In the code below, we have created the ”circle” class. The class contains the ”pi” static property, which has a constant value. class Circle { static pi: number = 3.14159; // Static property to hold the value of Pi } console.log(“The value of the PI is: ” + Circle.pi); On compiling, it will generate the following JavaScript code. var Circle = /** @class */ (function () { function Circle() { } Circle.pi = 3.14159; // Static property to hold the value of Pi return Circle; }()); console.log(“The value of the PI is: ” + Circle.pi); Output The output of the above generated JavaScript code is as follows − The value of the PI is: 3.14159 Example In the code below, we have defined the ”student” class. It contains the static property named ”studentCount” to store the total number of students. class Student { static studentCount: number = 0; // Static variable to store the count of students constructor(public name: string, public age: number) { this.name = name; this.age = age; Student.studentCount++; // Incrementing the count of students } // Method to display the student details display() { console.log(`Name: ${this.name}, Age: ${this.age}`); } } // Creating objects of Student class let student1 = new Student(”John”, 20); let student2 = new Student(”Doe”, 21); // Accessing static variable console.log(“Total number of registered students is: ” + Student.studentCount); // Output: 2 On compiling, it will generate the following JavaScript code. class Student { constructor(name, age) { this.name = name; this.age = age; this.name = name; this.age = age; Student.studentCount++; // Incrementing the count of students } // Method to display the student details display() { console.log(`Name: ${this.name}, Age: ${this.age}`); } } Student.studentCount = 0; // Static variable to store the count of students // Creating objects of Student class let student1 = new Student(”John”, 20); let student2 = new Student(”Doe”, 21); // Accessing static variable console.log(“Total number of registered students is: ” + Student.studentCount); // Output: 2 Output The output of the above generated JavaScript code is as follows − Total number of registered students is: 2 Static Methods You can use the ”static” keyword before the method name to declare the static method. Syntax You can follow the syntax below to define the static methods in TypeScript classes. class Class_name { static method_name(params) { // Code to be executed } } In the above syntax, the method_name method is a static method, which can take multiple parameters and return a value. You can call the static method by accessing it using the class name as shown in the code below. Class_name.method_name(); Example In the code below, the ”square” class contains the ”area()” static method, which gets the value of the square side as a parameter and returns the area of the square. class Square { // Define a static method static area(side: number) { return side * side; // return the area of the square } } // call the static method let area = Square.area(5); console.log(`Area of the square: ${area}`); // Output: Area of the square: 25 On compiling, it will generate the following JavaScript code. class Square { // Define a static method static area(side) { return side * side; // return the area of the square } } // call the static method let area = Square.area(5); console.log(`Area of the square: ${area}`); // Output: Area of the square: 25 Output The output of the above generated JavaScript code is as follows − Area of the square: 25 Example The below example is very similar to the second example covered in this lesson. It has a private static member named ”studentCount” to store the total number of students. class Student { private static studentCount: number = 0; // Static variable to store the count of students constructor(public name: string, public age: number) { this.name = name; this.age = age; Student.studentCount++; // Incrementing the count of students } // Method to get the count of students static getStudentCount() { return Student.studentCount; } } // Creating objects of Student class let student1 = new Student(”John”, 20); let student2 = new Student(”Doe”, 21); // Accessing static variable console.log(“Total number of registered students is: ” + Student.getStudentCount()); // Output: 2 On compiling, it will generate the following JavaScript code. class Student { constructor(name, age) { this.name = name; this.age = age; this.name = name; this.age = age; Student.studentCount++; // Incrementing the count of students } // Method to get the count of students static getStudentCount() { return Student.studentCount; } } Student.studentCount = 0; // Static variable to store the count of students // Creating objects of Student class let student1 = new Student(”John”, 20); let student2 =

TypeScript – Inheritance

TypeScript – Inheritance ”; Previous Next Inheritance in TypeScript is a concept that allows us to reuse the properties and methods of a single class with other classes. So, it increases the code readability by allowing the reuse of the codes of different classes. TypeScript is an object-oriented programming language, and it supports all features of the OOP. Object-oriented programming has four main pillars and inheritance is one of them. TypeScript mainly supports two types of inheritance: single-class inheritance and multilevel inheritance. We will explore each of them in this chapter. Single Class Inheritance In single-class inheritance, one class inherits the properties of another class. The class that inherits the properties of the other class is called the base class or child class. The class whose properties are inherited is called a parent or superclass. You can use the ”extend” keyword to achieve inheritance in TypeScript. Syntax You can follow the syntax below to use the single-class inheritance. class Child extends Parent { // Define properties and methods for child class } In the above syntax, we have used the ”extends” keyword between the name of the child and the parent class. Example In the code below, we have defined the ”Vehicle” class which contains the ”getType()” method, returning the vehicle type. class Vehicle { getType() { return “Vehicle”; } } // Define a class Car that extends Vehicle class Car extends Vehicle { carName: string = “Innova”; getCarName() { return this.carName; } } // Create an object of Car class let car = new Car(); console.log(car.getType()); // Output: Vehicle console.log(car.getCarName()); // Output: Innova On compiling, it will generate the following JavaScript code. class Vehicle { getType() { return “Vehicle”; } } // Define a class Car that extends Vehicle class Car extends Vehicle { constructor() { super(…arguments); this.carName = “Innova”; } getCarName() { return this.carName; } } // Create an object of Car class let car = new Car(); console.log(car.getType()); // Output: Vehicle console.log(car.getCarName()); // Output: Innova Output Vehicle Innova Super Keyword The super keyword is used to call the constructor of the Parent class or access and call the method of the Parent class. Syntax You can follow the syntax below to use the super keyword to call the constructor and methods of the Parent class in the Child class. class Child extends Parent { constructor() { super(); // To call the constructor of the parent class } super.method_name(); // To call method of the parent class } In the above syntax, we have used the ”super()” inside the constructor of the child class to call the constructor of the parent class. In ”super.method_name()”, method_name is the name of the method of the parent class. Example In the code below, we have defined the Person class which contains the ”name” property, and initialized it inside the constructor() method. The display() method prints the value of the name property. class Person { name: string; constructor(name: string) { this.name = name; } display(): void { console.log(this.name); } } // Employee class is inheriting the Person class class Employee extends Person { empCode: number; constructor(name: string, code: number) { super(name); this.empCode = code; } show(): void { super.display(); } } // Creating the object of Employee class let emp = new Employee(“Sam”, 123); emp.show(); // Sam On compiling, it will generate the following JavaScript code. class Person { constructor(name) { this.name = name; } display() { console.log(this.name); } } // Employee class is inheriting the Person class class Employee extends Person { constructor(name, code) { super(name); this.empCode = code; } show() { super.display(); } } // Creating the object of Employee class let emp = new Employee(“Sam”, 123); emp.show(); // Sam Output The above code example will produce the following result – Sam Method Overriding The method overriding concept allows you to override the code of the particular method of the parent class inside the child class. This way, you can have a method with the same name in the parent and child classes, having different functionalities. Example In the code below, the Animal class has a move() method which works for any animal. After that, we have extended the Dog class with the Animal class. The Dog class has its own move() method, and that”s how we do method overriding. class Animal { move() { console.log(“Animal is moving”); } } // Dog class is inheriting Animal class class Dog extends Animal { // Method overriding move() { console.log(“Dog is moving”); } } let dog = new Dog(); dog.move(); // Output: Dog is moving On compiling, it will generate the same JavaScript code. Output The above code example will produce the following result – Dog is moving Multilevel Inheritance Multilevel inheritance allows you to inherit the properties of the parent class, where the parent class also inherits the other class. Example In the code below, the Parrot class inherits the properties and methods of the Bird class, and the Bird class inherits the properties and methods of the Animal class. However, you may have more levels of multilevel inheritance in real-time development. class Animal { // Move method move() { console.log(”This animal moves”); } } // Bird class extends Animal class class Bird extends Animal { // Bird can fly fly() { console.log(”This bird flies”); } } // Parrot class inherits the Bird class class Parrot extends Bird { // Parrot can speak speak() { console.log(”The parrot speaks”); } } // Creating an instance of the Parrot class let P1 = new Parrot(); P1.speak(); On compiling, it will generate the same JavaScript code. Output The above code example will produce the following result – The parrot speaks Multiple Inheritance, Hierarchical Inheritance, and Hybrid Inheritance are also supported by some object-oriented programming languages but not supported by TypeScript. You may use the interface or prototype-based inheritance to achieve multiple inheritance. Print Page Previous Next Advertisements ”;

TypeScript – If Else Statement

TypeScript – If…else Statement ”; Previous Next In TypeScript, the if…else statement controls the program”s execution flow based on the different conditions. If the condition evaluates to true, the if block of code is executed. An if can be followed by an optional else block. The else block will execute if the Boolean expression tested by the if statement evaluates to false. Syntax The simple if…else statement in TypeScript is as follows – if(boolean_expression) { // statement(s) will execute if the boolean expression is true } else { // statement(s) will execute if the boolean expression is false } Flowchart The following flow chart shows how the if…else statement works. The if block guards the conditional expression. The block associated with the if statement is executed if the Boolean expression evaluates to true. The if block may be followed by an optional else statement. The instruction block associated with the else block is executed if the expression evaluates to false. Examples Let”s understand the if…else statement in details with the help of some examples in TypeScript. Example: Simple if…else In the example below, the variable num is assigned the value 12. The condition (num % 2 == 0) checks if num is even. Since 12 divided by 2 has no remainder, the condition evaluates to true, and the block code following the if statement executes. var num: number = 12; if (num % 2==0) { console.log(“Even”); } else { console.log(“Odd”); } On compiling, it will generate the following JavaScript code − var num = 12; if (num % 2 == 0) { console.log(“Even”); } else { console.log(“Odd”); } The above example prints whether the value in a variable is even or odd. The if block checks the divisibility of the value by 2 to determine the same. Here is the output of the above code − Even Example: Condition evaluates false In the above example, if you assign the value 13 to the variable num, the condition becomes false because 13 divided by 2 leaves a remainder of 1. So the block code following the else statement executes. var num: number = 13; if (num % 2==0) { console.log(“Even”); } else { console.log(“Odd”); } On compiling, it will generate the following JavaScript code. var num = 13; if (num % 2==0) { console.log(“Even”); } else { console.log(“Odd”); } Here the condition (13 % 2 == 0) evaluates to false and the else block executes. The output is as follows – Odd Example: else if statement let grade: number = 85; if (grade >= 90) { console.log(“Excellent”); } else if (grade >= 80) { console.log(“Great”); } else { console.log(“Keep studying”); } Here, the if statement first checks for the condition, grade >=90. If the condition evaluates to false, the else if statement checks for the condition, grade >= 80. Finally, else block executes only if conditions are false. On compiling, it will generate the following JavaScript code. let grade = 82; if (grade >= 90) { console.log(“Excellent”); } else if (grade >= 80) { console.log(“Great”); } else { console.log(“Keep studying”); } Here, the condition of the else if statement evaluates to true, so it prints “Great” as output. Great Print Page Previous Next Advertisements ”;

TypeScript – Useful Resources

TypeScript – Useful Resources ”; Previous Next The following resources contain additional information on TypeScript. Please use them to get more in-depth knowledge on this topic. Useful Video Courses Typescript Course: Learn Typescript from scratch Best Seller 61 Lectures 2.5 hours Skillbakery More Detail Three.js and TypeScript Course 78 Lectures 8 hours Sean Bradley More Detail TypeScript from Scratch: Go from zero to hero in TypeScript 78 Lectures 3.5 hours TELCOMA Global More Detail Learn Basic HTML, CSS & JavaScript (Typescript) with Svelte 31 Lectures 1 hours James Coonce More Detail Introduction to TypeScript 13 Lectures 1 hours Daniel Stern More Detail TypeScript For Beginners 45 Lectures 2 hours Dipendra Shekhawat More Detail Print Page Previous Next Advertisements ”;

TypeScript – Function Types

TypeScript – Function Types ”; Previous Next Function types in TypeScript allows us to define the types for the functions. Function type describes the shape of the function, including the parameters and return values. Function types consist of the following − Type of function parameters Return type of the function Typing a Function Typing a function refers to specifying types for the its parameters and return values. Similar to how we add types to variables, we can also add type annotations to function parameters and return values as we define for the variables. Let”s see how typing a function works with a simple function, function add (x: number, y: number): number { return x + y; } let addNums = function (x: number, y: number): number { return x + y; } In the first example, we added types for the parameters x and y and the return type of the function. TypeScript can infer the return type using the types of the parameters. This means that optionally we can leave the return type out. In the second example, we assigned a function to the variable addNums. While we didn”t explicitly define a type of addNums, TypeScript can infer its type. Let’s now check how TypeScript compiler infers the type of a variable assigned with a function. TypeScript infers the type of the variable In the below example, we have assigned a function to variable add − let add = function (a: number, b: number): number { return a + b; } The TypeScript compiler infers the type of the add variable as − (a: number, b: number) => number Look at the following screenshot, the typescript editor infers the type of the add variable. Here, “(a: number, b: number) => number” is basically a function type expression. The function type expression is a convenient way to declare a variable that hold a function. TypeScript Function Type Expression The function types in TypeScript can be defined using function type expressions. Function type expression is syntactically similar to the arrow function. Syntax Within function type expression, we specify the types of parameters and the return type. The syntax is as follows − (para1: type1, para2: type2, …) => returnType Where, (para1: type1, para2: type2, …): This defines the function’s parameters and their types. We can add multiple parameters separated by commas. =>: The fat arrow separates the parameters list from the return type. returnType: This is the type of the return value of function. Example to demonstrate the function type in TypeScript − (name: string) => void This function type is described as a function with one parameter, named name, of string type, that has no return value (indicated by void). (a: number, b: number) => number In the above function type, it takes two parameters named a and b of number types and return a value of type number. Example Let”s declare a variable named addFun of function type using function type expression − let addFun: (x: number, y: number) => number = function (x:number, y: number): number { return x + y } console.log(addFun(2, 3)); In the above example, we add a function to addFun that takes two number as parameters and returns their sum. The type annotation “(x: number, y: number) => number” clarifies this behavior. On compiling this TypeScript code, it will generate the following JavaScript code. let addFun = function (x, y) { return x + y; }; console.log(addFun(2, 3)); The output of the above example code is as follows − 5 Example Let”s take another example − const greet: (name: string) => string = (name) => { return `Hello, ${name}!`; }; console.log(greet(“Shahid”)); In the below example, we define a constant greet of type (name: string) => string. This function takes a string as a parameter and returns a string. The above TypeScript code will compile to the following JavaScript code. const greet = (name) => { return `Hello, ${name}!`; }; console.log(greet(“Shahid”)); The output of the above example code is as follows − Hello, Shahid! Declaring Function Type Variable In TypeScript, we can declare a variable with a specific function type using function type expression. Let’s declare a variable of function type − let add: (a: number, b: number) => number This declares a variable add of function type. The function takes two numbers as argument and returns a number. Example In the Example below, we declare the variable greet of the function type using function expression. And then assign the variable with a function that takes a parameter of type string and returns a string. let greet: (name: string) => string; greet = (name) => { return `Hello, ${name}!`; }; console.log(greet(”John”)); On compiling, it will generate the following JavaScript code − let greet; greet = (name) => { return `Hello, ${name}!`; }; console.log(greet(”John”)); The output is as follows − Hello, John! Specifying Function Parameters as Functions We can specify a parameter of type function. In the below example, the parameter fn is specified as of a function type. It accepts a parameter of type string and it does not return any value. The function greet accepts a parameter named fn, of type function. function greet (fn: (s: string) => void) { fn (“Welcome to Tutorials Point!”) } function print (str: string) { console.log(str); } greet(print); On compiling, it will generate the following JavaScript code. function greet(fn) { fn(“Welcome to Tutorials Point!”); } function print(str) { console.log(str); } greet(print); The output of the above example code is as follows − Welcome to Tutorials Point! Using Type Aliases to Function Types We can create a type alias to represent a specific function type and use it within out code − type funcType = (s: string) => void; function greet (fn: funcType) { fn (“Welcome to Tutorials Point!”) } function print (str: string) { console.log(str); } greet(print); Here we define a type alias functType for the function type “(s: string) => void”. Further we use funcType as type of parameter in the definition of

TypeScript – Decorators

TypeScript – Decorators ”; Previous Next Decorators in TypeScript are special kinds of declarations that can be attached to the class declaration, property, accessor, method, and parameters. It is used for the separate modification of the class without modifying the original source code. This makes them a powerful tool in the domain of object-oriented programming, allowing you to write cleaner, more organized code that adheres to the DRY (Don”t Repeat Yourself) principle. Using Decorators in TypeScript You are required to enable the ”experimentalDecorators” compiler option to enable the experimental support for decorators in your TypeScript project. There are 2 ways to enable ”experimentalDecorators” compiler option in TypeScript. You can use any option. Execute the below command in the terminal in the project directory. tsc –target ES5 –experimentalDecorators Or, you can update the tsconfig.js file and add “experimentalDecorators”: true attribute in compilerOptions object. { “compilerOptions”: { “target”: “ES5”, “experimentalDecorators”: true } } Decorator Syntax You can follow the syntax below to use decorators in TypeScript. @DecoratorName In the above syntax, ”DecoratorName” is a function name that is prefixed with the ”@” symbol. The expression must evaluate the ”DecorateName” function at the run time. Decorator Factories Whenever you need to customize how the decorator function is applied to declarations, they can use the decorator factories. A decorator factory function returns the expression which will be evaluated at the run time. Follow the syntax below to use the decorator factory function. function decoratorName(args: string) { // Decorator factory returns the function expression return function (target) { // This is the decorator which will be evaluated at the run time. }; } In the above syntax, ”args” is an argument passed to the decorator function, and ”target” is a prototype of the class. Decorator Composition You can use multiple decorators with particular declarations. Multiple decorators either can be used in a single line or multiline as shown below. In a single line: @f @g x OR, In multi lines: @f @g x In the above syntax, ”f” and ”g” decorators are used with a single declaration ”x”. Why Use Decorators? Let”s take a simple example to understand the use cases of decorators. // Defining a class class Student { // Declaring the properties of the class constructor(private name: string, private rollNo: number) { } // Defining the methods of the class sayHello() { console.log(`Hello, my name is ${this.name}.`); } printrollNo() { console.log(`My RollNo is ${this.rollNo}.`); } } // Creating an object of the class const user = new Student(“John”, 20); // Accessing the properties of the class user.sayHello(); user.printrollNo(); On compiling, it will generate the following JavaScript code: // Defining a class class Student { // Declaring the properties of the class constructor(name, rollNo) { this.name = name; this.rollNo = rollNo; } // Defining the methods of the class sayHello() { console.log(`Hello, my name is ${this.name}.`); } printrollNo() { console.log(`My RollNo is ${this.rollNo}.`); } } // Creating an object of the class const user = new Student(“John”, 20); // Accessing the properties of the class user.sayHello(); user.printrollNo(); It produces the following output: Hello, my name is John. My RollNo is 20. Now, what if we want to log the function when the execution of the function starts and ends? We need to add logs at the start and end of each function as shown in the below code. // Defining a class class Student { // Declaring the properties of the class constructor(private name: string, private rollNo: number) { } // Defining the methods of the class sayHello() { console.log(“Start: sayHello”); console.log(`Hello, my name is ${this.name}.`); console.log(“End: sayHello”); } printrollNo() { console.log(“Start: printrollNo”); console.log(`My RollNo is ${this.rollNo}.`); console.log(“End: printrollNo”); } } // Creating an object of the class const user = new Student(“John”, 20); // Accessing the properties of the class user.sayHello(); user.printrollNo(); On compiling, it will generate the following JavaScript code: // Defining a class class Student { // Declaring the properties of the class constructor(name, rollNo) { this.name = name; this.rollNo = rollNo; } // Defining the methods of the class sayHello() { console.log(“Start: sayHello”); console.log(`Hello, my name is ${this.name}.`); console.log(“End: sayHello”); } printrollNo() { console.log(“Start: printrollNo”); console.log(`My RollNo is ${this.rollNo}.`); console.log(“End: printrollNo”); } } // Creating an object of the class const user = new Student(“John”, 20); // Accessing the properties of the class user.sayHello(); user.printrollNo(); It will produce the following output: Start: sayHello Hello, my name is John. End: sayHello Start: printrollNo My RollNo is 20. End: printrollNo What if we want to reuse the logic of logging the function execution without writing the repeated code? Here, decorators come into the picture. Let”s learn it via the example below. // Decorator factory function printExecution(method: any, _context: any) { // Returning a new function return function (value: any, …args: any[]) { // Logging the method name at the start console.log(“start:”, method.name); // Calling the original method const result = method.call(value, …args); // Logging the method name at the end console.log(“end:”, method.name); return result; } } // Defining a class class Student { // Declaring the properties of the class constructor(private name: string, private rollNo: number) { } // Defining the methods of the class @printExecution sayHello() { console.log(`Hello, my name is ${this.name}.`); } @printExecution printrollNo() { console.log(`My RollNo is ${this.rollNo}.`); } } // Creating an object of the class const user = new Student(“John”, 20); // Accessing the properties of the class user.sayHello(); user.printrollNo(); The above code prints the same output as the previous code. Start: sayHello Hello, my name is John. End: sayHello Start: printrollNo My RollNo is 20. End: printrollNo Class Decorators Class decorators are used with the class declaration to observe or modify the class definition. Example // Decorator factory function LogClass(target: Function) { console.log(`${target.name} is instantiated`); } // Decorator @LogClass class MyClass { constructor() { console.log(“MyClass instance created”); } } // Create an instance of the class const myClassInstance = new MyClass(); On compilation, it will generate the following JavaScript code: // Class definition class MyClass { constructor() { console.log(“MyClass instance created”); }

TypeScript – Loops

TypeScript – Loops ”; Previous Next You may encounter situations, when a block of code needs to be executed several number of times. In general, statements are executed sequentially: The first statement in a function is executed first, followed by the second, and so on. Programming languages provide various control structures that allow for more complicated execution paths. A loop statement allows us to execute a statement or group of statements multiple times. Given below is the general form of a loop statement in most of the programming languages. TypeScript provides different types of loops to handle looping requirements. The following figure illustrates the classification of loops − Definite Loop A loop whose number of iterations are definite/fixed is termed as a definite loop. The for loop is an implementation of a definite loop. S.No. Loops & Description 1. for loop The for loop is an implementation of a definite loop. Indefinite Loop An indefinite loop is used when the number of iterations in a loop is indeterminate or unknown. Indefinite loops can be implemented using − S.No Loops & Description 1. while loop The while loop executes the instructions each time the condition specified evaluates to true. 2. do… while The do…while loop is similar to the while loop except that the do…while loop doesn’t evaluate the condition for the first time the loop executes. Example: while versus do..while var n:number = 5 while(n > 5) { console.log(“Entered while”) } do { console.log(“Entered do…while”) } while(n>5) The example initially declares a while loop. The loop is entered only if the expression passed to while evaluates to true. In this example, the value of n is not greater than zero, hence the expression returns false and the loop is skipped. On the other hand, the do…while loop executes statement once. This is because the initial iteration does not consider the Boolean expression. However, for the subsequent iteration, the while checks the condition and takes the control out of the loop. On compiling, it will generate following JavaScript code − var n = 5; while (n > 5) { console.log(“Entered while”); } do { console.log(“Entered do…while”); } while (n > 5); The above code will produce the following output − Entered do…while The break Statement The break statement is used to take the control out of a construct. Using break in a loop causes the program to exit the loop. Its syntax is as follows − Syntax break Flow diagram Example Now, take a look at the following example code − var i:number = 1 while(i<=10) { if (i % 5 == 0) { console.log (“The first multiple of 5 between 1 and 10 is : “+i) break //exit the loop if the first multiple is found } i++ } //outputs 5 and exits the loop On compiling, it will generate the following JavaScript code − var i = 1; while (i <= 10) { if (i % 5 == 0) { console.log(“The first multiple of 5 between 1 and 10 is : ” + i); break; //exit the loop if the first multiple is found } i++; } //outputs 5 and exits the loop It will produce the following output − The first multiple of 5 between 1 and 10 is : 5 The continue Statement The continue statement skips the subsequent statements in the current iteration and takes the control back to the beginning of the loop. Unlike the break statement, the continue doesn’t exit the loop. It terminates the current iteration and starts the subsequent iteration. Syntax continue Flowchart Example An example of the continue statement is given below − var num:number = 0 var count:number = 0; for(num=0;num<=20;num++) { if (num % 2==0) { continue } count++ } console.log (” The count of odd values between 0 and 20 is: “+count) //outputs 10 The above example displays the number of odd values between 0 and 20. The loop exits the current iteration if the number is even. This is achieved using the continue statement. On compiling, it will generate following JavaScript code. var num = 0; var count = 0; for (num = 0; num <= 20; num++) { if (num % 2 == 0) { continue; } count++; } console.log(” The count of odd values between 0 and 20 is: ” + count); //outputs 10 Output The count of odd values between 0 and 20 is: 10 The Infinite Loop An infinite loop is a loop that runs endlessly. The for loop and the while loop can be used to make an endless loop. Syntax: Infinite Loop using for loop for(;;) { //statements } Example: Infinite loop using for loop for(;;) { console.log(“This is an endless loop”) } Syntax: Infinite loop using while loop while(true) { //statements } Example: Infinite loop using while loop while(true) { console.log(“This is an endless loop”) } Print Page Previous Next Advertisements ”;

TypeScript – Optional Parameters

TypeScript – Optional Parameters ”; Previous Next The optional parameters in TypeScript allow us to specify function parameters may or may not be provided when calling the function. When a function is called without argument value for optional parameter, the default value of optional parameter is set to undefined. So inside the function body, we need to handle the optional parameter. A parameter can be made optional by adding a question mark after the its name in function definition. Syntax The syntax to defined a function with optional parameters in TypeScript is as follows − function functionName(para1:type1, para2?:type2): returnType{ // function body } In the above syntax, the function functionName is defined with two parameters − para1 and para2. The first parameter para1 is a required parameter and second parameter para2 is optional parameter. You can define a function with more than one optional parameters but the optional parameters must be the last parameters. JavaScript supports the optional parameters by default because in JavaScript, you can call a function without passing any argument even if it specifies the parameters. Examples Let’s understand the function optional parameters with the help of some programming examples in TypeScript. Example: Using Optional Function Parameters In the example below, the function sum accepts three parameters, x, y, and z. The first two parameters x, and y are required parameters and the third parameter z is optional parameter. We first check if the optional parameter is true or not. If it is passed, we return the sum of all parameters else we return the sum of only required parameters. Look at the example. function sum(x: number, y: number, z?: number): number { if (z){ return x + y + z; } else{ return x + y; } } console.log(sum(2,3)); console.log(sum(2,3,5)); On compiling, the above TypeScript code will be converted to the following JavaScript code. function sum(x, y, z) { if (z) { return x + y + z; } else { return x + y; } } console.log(sum(2, 3)); console.log(sum(2, 3, 5)); The output of the above example code is as follows − 5 10 Notice when we call the sum function with only two arguments (without optional parameter), the if condition becomes false. The default value of an optional parameter (missing argument) is undefined. Example: Type Guards for Option Parameters We can use a type guard to check if the parameter has a valid value before using it. In the below example, we use type guard typeof age === ”number” to check if age has a value before using it. function greet(name: string, age?: number): void { if (typeof age === ”number”) { console.log(`You are ${age} years old.`); } } greet(”Shahid”, 35); On compiling, it will produce the following JavaScript code. function greet(name, age) { if (typeof age === ”number”) { console.log(`You are ${age} years old.`); } } greet(”Shahid”, 35); The output of the above example code is as follows − You are 35 years old. Example: Optional parameters should be last parameters The optional parameters must be placed after the required parameters in the parameter list. function add (x?: number, y: number = 30){ return x + y; } console.log(add(2,3)); In the above example, the optional parameter is put before the required parameter. The TypeScript compiler will throw the following error − ”x” is possibly ”undefined”. Example: Optional parameters can”t have default values An optional parameter can’t be initialized with a default value. In the below example, we have initialized the parameter y optional with a default value, 30. function add (x: number, y?: number = 30){ return x + y; } console.log(add(2,3)); The TypeScript compiler will show the following error − Parameter cannot have question mark and initializer. The error shows that we can’t assign a parameter as both optional and default. How to deal with it? The default parameters are optional parameters also. Example: Default values for optional parameters A default parameter is automatically an optional parameter. The default values are used for missing arguments if the function is called with missing values. function greet(name: string, age: number = 35): void { console.log(`Hello, ${name}!`); console.log(`You are ${age} years old.`); } greet(”Shahid”); In the above example, we define the function greet with two parameters − name and age. The second parameter, age is initialized with default value. The parameter age works here as optional parameter. On compiling, it will generate the following JavaScript code. function greet(name, age = 35) { console.log(`Hello, ${name}!`); console.log(`You are ${age} years old.`); } greet(”Shahid”); The output of the above example code is as follows − Hello, Shahid! You are 35 years old. Print Page Previous Next Advertisements ”;