TypeScript – Template Literal Types ”; Previous Next Template string literals are used to create dynamic strings with variables in JavaScript. Similarly, in TypeScript you can use template literal types to create the dynamic types, which is introduced in the TypeScript 4.1 version. The syntax of the template literal types in TypeScript is very similar to the JavaScript template string literals. Syntax You can follow the syntax below to use the template literal types in TypeScript. type type_name = `some_text ${variable_name}` In the above syntax, ”type_name” is the name of the type. You need to use the backticks (“) to define template literal types. The ”some_text” can be any string value that will remain constant. To add any dynamic value in the type, you need to add the variable name inside the ”${}” structure. Examples Let”s understand the Template Literal Types in details with the help of some examples in TypeScript. Example: Basic Use In the code below, we have defined the ”World” type which contains the “World” as a value. The ”Greeting” type is a template literal type whose value changes based on the value of the ”World” variable. Next, we created the ”greeting” variable of type ”Greeting” which contains a “Hello World” value. If we try to assign another value to it, the TypeScript compiler throws an error. type World = “world”; // Defining a template literal type type Greeting = `Hello, ${World}`; const greeting: Greeting = “Hello, world”; // Correct // const wrongGreeting: Greeting = “Hello, everybody”; // Error: This type is “Hello, world” specifically. console.log(greeting); On compiling, it will generate the following JavaScript code: const greeting = “Hello, world”; // Correct // const wrongGreeting: Greeting = “Hello, everybody”; // Error: This type is “Hello, world” specifically. console.log(greeting); The above example code will produce the following output: Hello, world Example: Combining with Union Types In this code, the ”size” type contains the union of multiple type values. The ”ResponseMessage” type is a template literal type whose value changes based on the value of the ”Size” type. The selectSize() function takes a string of type ”Size” as a parameter, and returns the value of type ”ResponseMessage”. Next, we call the function by passing ”medium” as a function parameter. If we try to pass any other string value than the ”small”, ”medium”, and ”large” as a function parameter, it will throw an error. // Creating a type using literal type type Size = “small” | “medium” | “large”; // Custom template literal type type ResponseMessage = `${Size} size selected`; // Function to select size function selectSize(size: Size): ResponseMessage { return `${size} size selected`; } // Call the function const response: ResponseMessage = selectSize(“medium”); // “medium size selected” console.log(response); On compiling, it will generate the following JavaScript code: // Function to select size function selectSize(size) { return `${size} size selected`; } // Call the function const response = selectSize(“medium”); // “medium size selected” console.log(response); Its output is as follows: medium size selected Example: Conditional String Patterns In this example, we have used the generic types with constraints. Here, ”T extends Status” means, the value of T can be only from the status. The statusMessage type is a combination of the type ”T” and ”status” strings. The printStatus() function takes the type T as a parameter, which can be any one value from the ”Status” type, and returns the value of type ”statusMessage”. Next, we have called the printStatus() function by passing the “loading” value which is a part of the ”Status” type. // Definition of the Status type type Status = “loading” | “success” | “error”; // T can be any of the values in the Status type type StatusMessage<T extends Status> = `${T}Status`; // Function to return a message based on the status function printStatus<T extends Status>(status: T): StatusMessage<T> { return `${status} Status` as StatusMessage<T>; } // Call the function with the “loading” status const loadingMessage = printStatus(“Loading”); // “loadingStatus” console.log(loadingMessage); On compiling, it will generate the following JavaScript code: // Function to return a message based on the status function printStatus(status) { return `${status} Status`; } // Call the function with the “loading” status const loadingMessage = printStatus(“Loading”); // “loadingStatus” console.log(loadingMessage); Its output is as follows: Loading Status Example: API Route Generation The below example demonstrates the real-time practical use of the template literal types. Then, We have defined the Method type which can have any value from the REST API method type. The Entity type defines the entity objects. The getRoute() method takes the entity and method of type Entity and Method, respectively as a parameter. It returns the string value of type APIRoute after combining the entity and method values. // Defining the Method and Entity types type Method = “get” | “post” | “delete”; type Entity = “user” | “post”; // Defining the ApiRoute type type ApiRoute = `/${Entity}/${Method}`; // Defining the getRoute function function getRoute(entity: Entity, method: Method): ApiRoute { return `/${entity}/${method}` as ApiRoute; } // Using the getRoute function const userRoute = getRoute(“user”, “post”); // “/user/post” console.log(userRoute); On compiling, it will generate the following JavaScript code: // Defining the getRoute function function getRoute(entity, method) { return `/${entity}/${method}`; } // Using the getRoute function const userRoute = getRoute(“user”, “post”); // “/user/post” console.log(userRoute); Its output is as follows: /user/post In TypeScript, the template literal type is mainly used when you need to create dynamic types. Print Page Previous Next Advertisements ”;
Category: typescript
TypeScript – Creating Types from Types ”; Previous Next TypeScript allows you to create custom types from the existing or built-in types. Creating types from existing types helps you to make code more maintainable and error-resistant. TypeScript is a statically typed language. This means that ideally, each variable, function parameter, and object property should be explicitly assigned a type. Here we will discuss different ways to create custom types from the existing types. Union Types If you want to define a single variable that can store the value of multiple data types, you can use the union operator to combine multiple operators. The union operator is ”|”, and using that you can combine multiple types. Syntax You can follow the syntax below to create custom types by using the union operator. type unionTypes = type1 | type2 | type3 | …; In the above syntax, type1, type2, type3, etc. are data types. Example In the code below, we have defined the ”StringOrNumber” custom type which is a union of the string and number data type. The processValue() function takes the single parameter of the type ”StringOrNumber”. In the function body, we check the type of the parameter using the ”typeof” operator, and based on the string or numeric type, we print the value in the output console. // Defining a union type type StringOrNumber = string | number; // Function that accepts a union type as an argument function processValue(value: StringOrNumber) { // Check if the value is a string or number type if (typeof value === “string”) { console.log(`String: ${value}`); } else { console.log(`Number: ${value}`); } } processValue(“hello”); // Output: String: hello processValue(123); // Output: Number: 123 On compiling, it will generate the following JavaScript code. // Function that accepts a union type as an argument function processValue(value) { // Check if the value is a string or number type if (typeof value === “string”) { console.log(`String: ${value}`); } else { console.log(`Number: ${value}`); } } processValue(“hello”); // Output: String: hello processValue(123); // Output: Number: 123 The output of the above example code is as follows – String: hello Number: 123 Intersection Types The intersection operator (&) allows you to combine the multiple types in the single types. For example, if you have two interfaces or types for Business and contactDetails, and want to combine both types, you can use the intersection operator. Syntax You can follow the syntax below to create custom types by using the intersection operator. type intersectionTypes = type1 & type2 & type3 & …; In the above syntax, we have combined multiple types using the intersection operator. Example In the code below, we have defined the ”Business” interface containing the name and turnover properties. We have also defined the contactDetails interface containing the email and phone properties. After that, we combined both types using the intersection operator and stored them in the ”BusinessContact” type. Next, we have defined the object of the type ”BusinessContact”, and logged it in the console. // Defining a business type interface Business { name: string; turnover: number; } // Defining a contact details type interface ContactDetails { email: string; phone: string; } // Intersection of two types type BusinessContact = Business & ContactDetails; // Creating an object of the type BusinessContact let contact: BusinessContact = { name: “EnviroFront”, turnover: 5000000, email: “[email protected]”, phone: “1234567890” }; console.log(contact); On compiling, it will generate the following JavaScript code. // Creating an object of the type BusinessContact let contact = { name: “EnviroFront”, turnover: 5000000, email: “[email protected]”, phone: “1234567890” }; console.log(contact); The output of the above example code is as follows – { name: ”EnviroFront”, turnover: 5000000, email: ”[email protected]”, phone: ”1234567890” } Utility types TypeScript contains multiple utility types, which makes it easy to transform the particular types and create new types. Let”s look at some of the utility types with examples. Syntax You can follow the syntax below to use any utility type. Utility_type_name<type or interface> In the above syntax, ”utility_type_name” can be replaced with ”Partial”, ”Pick”, ”Record”, etc. based on which utility type you are using. Here, ”type” or ”interface” is the name of the interface from which you want to create a new custom type. Partial Utility Type The partial utility type makes all properties of the interface or type option. So, you can create a new type having all properties optional from the existing type. Example In the code below, we have defined the ”Todo” interface. After that, we used the Partial utility type to create a new type using the Todo interface by making all properties of it optional. Next, we have defined the object of the ”OptionalTodo” type, which contains only the ”title” property, as the ”description” property is optional. // Defining an interface for Todo list interface Todo { title: string; description: string; } // Defining a custom type using the Partial utility type type OptionalTodo = Partial<Todo>; // Creating an object of type OptionalTodo let todo: OptionalTodo = { title: “Buy milk” }; // ”description” is optional console.log(todo); On compiling, it will generate the following JavaScript code. // Creating an object of type OptionalTodo let todo = { title: “Buy milk” }; // ”description” is optional console.log(todo); The output of the above example code is as follows – { title: ”Buy milk” } Pick Utility Type The Pick utility type allows one to pick a subset of properties from the existing types. Let”s understand it via the example below. Example In the code below, we have defined the ”ToDo” interface and used the Pick utility type to create a new type with only the ”title” property from the ”ToDo” interface. Here, the ”ToDoPick” type contains only the ”title” property. // Defining an interface for Todo list interface Todo { title: string; description: string; } // Defining a custom type using the Pick utility type type TodoPick = Pick<Todo, “title”>; let myTodo: TodoPick = { title: “Write a code” }; console.log(myTodo.title); On compiling, it will generate the following JavaScript code. let myTodo =
TypeScript – Type Annotations ”; Previous Next Type Annotations In TypeScript,type annotations offer a way to define (or annotate) the data types of variables, class members, function parameters and return values. TypeScript is a statically typed programming language that optionally supports the dynamic typing. Because of this support any JavaScript file (.js) can be directly renamed as a TypeScript file (.ts). As we know JavaScript is a dynamically typed programming language and TypeScript is the superset of the JavaScript. TypeScript supports all the functionalities of JavaScript plus some additional features. TypeScript provides the way how to annotate the datatype. By the term “type annotations” means assigning the datatypes. Variable Type Annotations TypeScript supports static typing of variables. We can annotate the types of variables while declaring them. Also TypeScript optionally support the dynamic typing as JavaScript. For example, when we define a variable that holds a number, we can define it as follows – var x = 10; The above declaration is absolutely permissible in TypeScript as it supports the dynamic typing. We can annotate the datatype of the variable x as follows – var x: number = 10; To do a type annotation, you can use colon (:) sign after the variable name followed by datatype of the variable. var varName: datatype Followings are the different examples to annotate a variable with different datatypes. let name: string; let age: number; let isEnrolled: boolean; In the example above, we added string as type of variable name. Similarly, age and isEnrolled are annotated with number and boolean type. Example Let”s try the following example. In this example, we have declared two variables, pName, and pAge. We have annotated pName as string and pAge as number. let pName: string; let pAge: number; pName = “John Doe”; pAge = 35; console.log(`Name of the person is ${pName} and his age is ${pAge}`); On compiling, TypeScript compiler will produce the following JavaScript code – let pName; let pAge; pName = “John Doe”; pAge = 35; console.log(`Name of the person is ${pName} and his age is ${pAge}`); The output of the above JavaScript code is as follows – Name of the person is John Doe and his age is 35 Function Type Annotations You can add the type to a function in TypeScript. A function”s type has two parts – the function parameters and the return type of the function. Function Parameter Type Annotation We can annotate the datatypes of the parameters in the function definition. function displayDetails(id: number, name: string){ console.log(“ID:”, id); console.log(“Name”, name); } displayDetails(123,”John”); On compiling, it will produce the following JavaScript code – function displayDetails(id, name) { console.log(“ID:”, id); console.log(“Name:”, name); } displayDetails(123, “John”); The result of the above example code is as follows – ID: 123 Name: John Function Return Type Annotation You can add the datatype of the function return. It will be the datatype of the value returned by the function. function add (x: number, y: number): number { return x + y; } If you are not writing a return type then, the default return type of any function will be undefined. If a function is not returning any value then, you should use void as function return type instead of leaving it off. For example, instead of writing the following – function greet(name: string){ console.log(`Hello Mr. ${name}. Welcome to Tutorials Point.`); } Write the function using void as return type as follows – function greet(name: string): void { console.log(`Hello Mr. ${name}. Welcome to Tutorials Point.`); } Example In the example below, we annotate the function parameters and its return type. The function add take two parameters – x and, y of number type and also a value of number type. The returned value is the sum of the passed arguments to the function. function add(x: number, y: number): number { return x + y; } console.log(add(2,3)) On compiling, it will produce the following JavaScript code – function add(x, y) { return x + y; } console.log(add(2, 3)); The output of the above code is as follows − 5 Object Properties Type Annotations You can use the type annotation to add the types to the properties of an object. Let”s define an object using interface as follows − interface Person { name: string; age: number; } const person: Person = { name: “John Doe”, age: 35, } In the above example, we added types string and number to the properties name and age respectively. You can assign only string value to the name property and similarly only number value to the age property. Suppose if you try to add a string to age, it will throw an error. Type ”string” is not assignable to type ”number”. Example Let”s take a complete example. In this example, we define an interface named Person with two properties – name and age. The name property is annotated as string and age is as number. We create an object named person using the interface Person. Then finally, we display the object properties in the console. interface Person { name: string; age: number; } const person: Person = { name: “John Doe”, age: 35, } console.log(`The person”s name is ${person.name} and person”s age is ${person.age}`); On compiling, it will produce the following JavaScript code − const person = { name: “John Doe”, age: 35, }; console.log(`The person”s name is ${person.name} and person”s age is ${person.age}`); The output of the above example code if as follows − The person”s name is John Doe and person”s age is 35 The type annotations of variables, function parameters and return types, etc. are recommended in TypeScript. But also TypeScript supports dynamic typing as in JavaScript. As you already know that TypeScript supports all ECMAScript features. Print Page Previous Next Advertisements ”;
TypeScript – Classes
TypeScript – Classes ”; Previous Next TypeScript is object oriented JavaScript. TypeScript supports object-oriented programming features like classes, interfaces, etc. A class in terms of OOP is a blueprint for creating objects. A class encapsulates data for the object. Typescript gives built in support for this concept called class. JavaScript ES5 or earlier didn’t support classes. Typescript gets this feature from ES6. Creating classes Use the class keyword to declare a class in TypeScript. The syntax for the same is given below − Syntax class class_name { //class scope } The class keyword is followed by the class name. The rules for identifiers must be considered while naming a class. A class definition can include the following − Fields − A field is any variable declared in a class. Fields represent data pertaining to objects Constructors − Responsible for allocating memory for the objects of the class Functions − Functions represent actions an object can take. They are also at times referred to as methods These components put together are termed as the data members of the class. Consider a class Person in typescript. class Person { } On compiling, it will generate following JavaScript code. //Generated by typescript 1.8.10 var Person = (function () { function Person() { } return Person; }()); Example: Declaring a class class Car { //field engine:string; //constructor constructor(engine:string) { this.engine = engine } //function disp():void { console.log(“Engine is : “+this.engine) } } The example declares a class Car. The class has a field named engine. The var keyword is not used while declaring a field. The example above declares a constructor for the class. A constructor is a special function of the class that is responsible for initializing the variables of the class. TypeScript defines a constructor using the constructor keyword. A constructor is a function and hence can be parameterized. The this keyword refers to the current instance of the class. Here, the parameter name and the name of the class’s field are the same. Hence to avoid ambiguity, the class’s field is prefixed with the this keyword. disp() is a simple function definition. Note that the function keyword is not used here. On compiling, it will generate following JavaScript code. //Generated by typescript 1.8.10 var Car = (function () { //constructor function Car(engine) { this.engine = engine; } //function Car.prototype.disp = function () { console.log(“Engine is : ” + this.engine); }; return Car; }()); Creating Instance objects To create an instance of the class, use the new keyword followed by the class name. The syntax for the same is given below − Syntax var object_name = new class_name([ arguments ]) The new keyword is responsible for instantiation. The right-hand side of the expression invokes the constructor. The constructor should be passed values if it is parameterized. Example: Instantiating a class var obj = new Car(“Engine 1”) Accessing Attributes and Functions A class’s attributes and functions can be accessed through the object. Use the ‘ . ’ dot notation (called as the period) to access the data members of a class. //accessing an attribute obj.field_name //accessing a function obj.function_name() Example: Putting them together class Car { //field engine:string; //constructor constructor(engine:string) { this.engine = engine } //function disp():void { console.log(“Function displays Engine is : “+this.engine) } } //create an object var obj = new Car(“XXSY1”) //access the field console.log(“Reading attribute value Engine as : “+obj.engine) //access the function obj.disp() On compiling, it will generate following JavaScript code. //Generated by typescript 1.8.10 var Car = (function () { //constructor function Car(engine) { this.engine = engine; } //function Car.prototype.disp = function () { console.log(“Function displays Engine is : ” + this.engine); }; return Car; }()); //create an object var obj = new Car(“XXSY1”); //access the field console.log(“Reading attribute value Engine as : ” + obj.engine); //access the function obj.disp(); The output of the above code is as follows − Reading attribute value Engine as : XXSY1 Function displays Engine is : XXSY1 Class Inheritance TypeScript supports the concept of Inheritance. Inheritance is the ability of a program to create new classes from an existing class. The class that is extended to create newer classes is called the parent class/super class. The newly created classes are called the child/sub classes. A class inherits from another class using the ‘extends’ keyword. Child classes inherit all properties and methods except private members and constructors from the parent class. Syntax class child_class_name extends parent_class_name However, TypeScript doesn’t support multiple inheritance. Example: Class Inheritance class Shape { Area:number constructor(a:number) { this.Area = a } } class Circle extends Shape { disp():void { console.log(“Area of the circle: “+this.Area) } } var obj = new Circle(223); obj.disp() On compiling, it will generate following JavaScript code. //Generated by typescript 1.8.10 var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Shape = (function () { function Shape(a) { this.Area = a; } return Shape; }()); var Circle = (function (_super) { __extends(Circle, _super); function Circle() { _super.apply(this, arguments); } Circle.prototype.disp = function () { console.log(“Area of the circle: ” + this.Area); }; return Circle; }(Shape)); var obj = new Circle(223); obj.disp(); The output of the above code is as follows − Area of the Circle: 223 The above example declares a class Shape. The class is extended by the Circle class. Since there is an inheritance relationship between the classes, the child class i.e. the class Car gets an implicit access to its parent class attribute i.e. area. Inheritance can be classified as − Single − Every class can at the most extend from one parent class Multiple − A class can inherit from multiple classes. TypeScript doesn’t support multiple inheritance. Multi-level − The following example shows how multi-level inheritance works. Example class Root { str:string; } class Child extends Root {} class Leaf extends Child {}
TypeScript – Intersection Types ”; Previous Next In TypeScript, an intersection type combines multiple types into one. Although intersection and union types in TypeScript are similar, they are used in very different ways. A type that combines different types into one is called an intersection type. This enables you to combine many types to produce a single type with all the necessary attributes. Members from each of the provided types will be present in an object of this type. The intersection type is made using the ”&” operator. When two types intersect in TypeScript, the intersection type will inherit the characteristics of both intersecting types. Take caution when combining types that share property names with different kinds. Syntax We can write the below syntax to create an Intersection type in TypeScript. type intersepted_Type = Type1 & Type2; Example In the example below, we have created two interfaces named “Book” and “Author”. Now inside the Book, we have created two fields named “book_id”, which is of number type, and “book_name”, which is of string type. And inside the Author, we have also created two fields named “author_id”, which is of number type, and “author_name”, which is of string type. Next, we intersected the Book and Author interface and stored it into intersected_types. Finally, values are retrieved from an object of the intersection type created. interface Book { book_id: number book_name: string } interface Author { author_id: number author_name: string } type intersected_type = Book & Author let intersected_type_object1: intersected_type = { book_id: 101, book_name: ”Typescript is Awesome”, author_id: 202, author_name: ”Tutorialspoint!”, } console.log(”Book Id: ” + intersected_type_object1.book_id) console.log(”Book name: ” + intersected_type_object1.book_name) console.log(”Author Id: ” + intersected_type_object1.author_id) console.log(”Author name: ” + intersected_type_object1.author_name) On compiling, it will generate the following JavaScript code − var intersected_type_object1 = { book_id: 101, book_name: ”Typescript is Awesome”, author_id: 202, author_name: ”Tutorialspoint!” }; console.log(”Book Id: ” + intersected_type_object1.book_id); console.log(”Book name: ” + intersected_type_object1.book_name); console.log(”Author Id: ” + intersected_type_object1.author_id); console.log(”Author name: ” + intersected_type_object1.author_name); Output The above code will produce the following output – Book Id: 101 Book name: Typescript is Awesome Author Id: 202 Author name: Tutorialspoint! As users can see in the output, all the values of two different interfaces are combined and displayed. Intersection types are Associative and Commutative The commutative property indicates that an equation”s factors can be freely rearranged without altering the equation”s outcome. commutative property: (A & B) = (B & A) Associative property asserts that altering how integers are grouped during an operation will not affect the equation”s solution. associative property: (A & B) & C = A & (B & C) When we cross two or more kinds, it doesn”t matter what order they are in. The ”typeof” operator is used to verify that the attributes of the intersected objects are also the same, regardless of how the items are intersected or in what order. Example As we can see in the below example, here we have created three interfaces named “Student”, “Class”, and “Subject”. Now inside the Student, we have created two fields called “student_id”, which is of number type, and “sudent_name”, which is of string type. Inside the “Class” instance, we have also created two fields named “class_id”, which is of number type, and “class_name”, which is of string type. Inside the “Subject” instance, we have also created two fields named “subject_id”, which is of number type, and “subject_name”, which is of string type. Next, we intersected the Book, Author, and Subject interface using associative property and stored it into intersected types. After that, values are retrieved from an object of the intersection type created. Finally, we checked the objects using the typeof operator and logged in to the console. interface Student { student_id: number student_name: string } interface Class { class_id: number class_name: string } interface Subject { subject_id: number subject_name: string } type intersected_type_1 = (Student & Class) & Subject type intersected_type_2 = Student & (Class & Subject) let intersected_type_object1: intersected_type_1 = { student_id: 101, student_name: ”Typescript”, class_id: 10, } let intersected_type_object2: intersected_type_2 = { student_id: 102, student_name: ”Typescript2”, class_id: 11, } console.log(typeof intersected_type_object1 === typeof intersected_type_object2) On compiling, it will generate the following JavaScript code − var intersected_type_object1 = { student_id: 101, student_name: ”Typescript”, class_id: 10 }; var intersected_type_object2 = { student_id: 102, student_name: ”Typescript2”, class_id: 11 }; console.log(typeof intersected_type_object1 === typeof intersected_type_object2); Output The above code will produce the following output − true As users can see in the output, both the attributes of the objects are identical, showing the true value. Print Page Previous Next Advertisements ”;
TypeScript – Duck-Typing
TypeScript – Duck Typing ”; Previous Next Duck Typing The circumstance where an object”s type is decided by its behavior, like methods and attributes, rather than its class is known as “duck typing”. The usage of interfaces in TypeScript makes duck typing possible. Where interface means the set of methods and characteristics an object must have to fall under that type are described. For example, if an interface defines the function, any object with the method called “myFunc()” may be treated as belonging to a specific kind, regardless of its class. Duck typing emphasizes assessing an object”s suitability for a task by considering its methods and attributes instead of its actual type. An interface explains the set of properties and methods an object must have to be considered “duck typed” for a particular purpose. Benefits of Duck Typing One of duck typing”s main benefits is making code more flexible and reusable. The code works with any object with the required methods and properties rather than just particular types of objects and may be used in various situations without requiring modification. Duck typing also improves code reuse by enabling the interchangeable usage of objects of diverse kinds within a single codebase. Exmaples of Duck Typing is TypeScript Here is an example of how to use duck typing in TypeScript − Define an interface that represents the behaviour you want an object to have. For example − interface Duck { quack(): void; } Create a class that implements the interface. For example − class MallardDuck implements Duck { quack(): void { console.log(“Quack!”); } } Create an instance of the class and use it as the type defined by the interface. let duck: Duck = new MallardDuck(); duck.quack(); // Output: “Quack!” Create another class that also implements the interface − class RubberDuck implements Duck { quack(): void { console.log(“Squeak!”); } } Use the new class instance as the same type defined by the interface. let duck: Duck = new RubberDuck(); duck.quack(); // Output: “Squeak!” As you can see, both MallardDuck and RubberDuck classes implement the Duck interface, and the duck variable can be assigned to instances of both classes. The type is determined by the behaviour (methods and properties) defined in the interface rather than the class. It”s also important to note that in typescript, you can use the typeof keyword to check the type of object in runtime and if the object has the expected method or property. Example In this example, the Bird and Plane classes implement the Flyable interface, which requires a fly() method. Both “duck types” can be used interchangeably in the goFly() function. The function doesn”t care about the actual type of the object passed to it as long as it has a fly() method that can be called. interface Flyable { fly(): void; } class Bird implements Flyable { fly(): void { console.log(“Bird is flying”); } } class Plane implements Flyable { fly(): void { console.log(“Plane is flying”); } } function goFly(flyable: Flyable) { flyable.fly(); } let bird = new Bird(); let plane = new Plane(); goFly(bird); // Prints “Bird is flying” goFly(plane); // Prints “Plane is flying” On compiling, it will generate the following JavaScript code − var Bird = /** @class */ (function () { function Bird() { } Bird.prototype.fly = function () { console.log(“Bird is flying”); }; return Bird; }()); var Plane = /** @class */ (function () { function Plane() { } Plane.prototype.fly = function () { console.log(“Plane is flying”); }; return Plane; }()); function goFly(flyable) { flyable.fly(); } var bird = new Bird(); var plane = new Plane(); goFly(bird); // Prints “Bird is flying” goFly(plane); // Prints “Plane is flying” Output The above code will produce the following output – Bird is flying Plane is flying Example Overall, duck typing is a powerful programming concept that allows for greater flexibility and reusability in TypeScript code by allowing objects of different types to be used interchangeably as long as they have the same methods and properties. In this example, the Driveable interface, Car and Truck classes show the same thing. interface Driveable { drive(): void; } class Car implements Driveable { drive(): void { console.log(“Car is driving”); } } class Truck implements Driveable { drive(): void { console.log(“Truck is driving”); } } function goDrive(driveable: Driveable) { driveable.drive(); } let car = new Car(); let truck = new Truck(); goDrive(car); // Prints “Car is driving” goDrive(truck); // Prints “Truck is driving” On compiling, it will generate the following JavaScript code − var Car = /** @class */ (function () { function Car() { } Car.prototype.drive = function () { console.log(“Car is driving”); }; return Car; }()); var Truck = /** @class */ (function () { function Truck() { } Truck.prototype.drive = function () { console.log(“Truck is driving”); }; return Truck; }()); function goDrive(driveable) { driveable.drive(); } var car = new Car(); var truck = new Truck(); goDrive(car); // Prints “Car is driving” goDrive(truck); // Prints “Truck is driving” Output The above code will produce the following output – Car is driving Truck is driving The main idea behind duck typing is that the code should be written to work with any object with the methods and properties it needs, rather than being written to work with specific objects. This can make the code more flexible and reusable, allowing you to use different types of objects interchangeably without changing the code. Print Page Previous Next Advertisements ”;
TypeScript – Default Parameters ”; Previous Next Default Parameters In TypeScript, we can assign the function parameters some values by default. Such parameters can be explicitly passed values. These parameters are known as default parameters. When a function is called with missing arguments, or argument with undefined values, the function uses these default initialized values. Syntax The syntax of the default parameters in TypeScript is as follows – function functionName(param1[:type], param2[:type] = defaultValue) Here the function functionName() takes two parameters – param1 and param2. The first parameter param1 is required parameter whereas the second parameter param2 is a default parameter. The param2 is initialized with a default value, defaultValue. When the function functionName() is called without passing the value for param2, the defaultValue is used as the value of param2. Let’s understand the function default parameters with the help of some TypeScript example programs. Example: Simple Default Parameters let”s look at the following example, function greet(name: string, age: number = 30){ console.log(`Hi ${name}, your age is ${age}.`) } greet(”John”, 50); greet(”John”); In the example above, the parameter age is a default parameter that is initialized with default value of 30. The parameter name is a required parameter. On compiling, it will generate the following JavaScript code. function greet(name, age = 30) { console.log(`Hi ${name}, your age is ${age}.`); } greet(”John”, 50); greet(”John”); Output Hi John, your age is 50. Hi John, your age is 30. Example: Default parameters after required parameters Default Parameters should come after Required Parameters in the function definition In the following example, we put the default parameter y after the required parameter x. function sum(x: number, y: number=10): number{ return x + y; } console.log(sum (20,30)); console.log(sum (30)); On compiling, it will generate the following JavaScript code. function sum(x, y = 10) { return x + y; } console.log(sum(20, 30)); console.log(sum(30)); The output is as follows – 50 40 Example: Default parameters before required parameters But if you put the default parameter before the required parameter, and call the function without the passing value for default argument it will show an error. Let”s look at the following example – function sum(x: number=10, y:number):number{ return x + y; } console.log(sum(20,30)); // 50 console.log(sum(30)); // NaN The above TypeScript program will show the following error – Expected 2 arguments, but got 1. And produce the following output – 50 NaN Example: Passing a function as a value for default parameter In the example below, we initialized the parameter b with getNum() function as default value. The getNum() function return the number 10. When the second argument is missing, the value returned by the function getNum() is used as the value for the parameter inside the function. function getNum(): number { return 10; } function mul(a: number, b = getNum()) { return a * b; } console.log(mul(20, 5)); console.log(mul(20)) Output 100 200 Optional Parameter vs. Default Parameter We can call a function without passing a value for the default parameter. We can also call a function without passing a value for optional parameter. Example: Default Parameter In the example below, the age parameter has default value as 30. Which means if you are not passing a value for the age parameter, the function will use the default value of 30 for age. function greet(name: string, age: number = 30){ console.log(`Hi ${name}, your age is ${age}.`); } greet(”John”, 50); greet(”John”); On compiling, it will generate the following JavaScript code. function greet(name, age = 30) { console.log(`Hi ${name}, your age is ${age}.`); } greet(”John”, 50); greet(”John”); The output of the above example code is as follows – Hi John, your age is 50. Hi John, your age is 30. Example: Optional Parameter In the below example, the age parameter is optional. This means you can call the greet function without passing a value for age parameter. When called without a value of age parameter. function greet(name: string, age?:number){ if (age) { console.log(`Hello ${name}, you are ${age} years old`); } else{ console.log(`Hello ${name}`); } } greet (”Shahid”, 35); greet (”Shahid”); On compiling, it will generate the following JavaScript. function greet(name, age) { if (age) { console.log(`Hello ${name}, you are ${age} years old`); } else { console.log(`Hello ${name}`); } } greet(”Shahid”, 35); greet(”Shahid”); The output of the above code is as follows – Hello Shahid, you are 35 years old Hello Shahid We can”t declare a parameter optional and default at the same time. function greet(name: string, age?: number = 30){ console.log(`Hi ${name}, your age is ${age}.`); } The above program will show the following error – Parameter cannot have question mark and initializer. Print Page Previous Next Advertisements ”;
TypeScript – Functions
TypeScript – Functions ”; Previous Next Functions in TypeScript are the building blocks of readable, maintainable, and reusable code. A function is a set of statements to perform a specific task. Functions organize the program into logical blocks of code. Once defined, functions may be called to access code. This makes the code reusable. Moreover, functions make it easy to read and maintain the program’s code. A function declaration tells the compiler about a function”s name, return type, and parameters. A function definition provides the actual body of the function. Sr.No Funtions & Description 1. Defining a Function A function definition specifies what and how a specific task would be done. 2. Calling a Function A function must be called so as to execute it. 3. Returning Functions Functions may also return value along with control, back to the caller. 4. Parameterized Function Parameters are a mechanism to pass values to functions. Optional Parameters Optional parameters can be used when arguments need not be compulsorily passed for a function’s execution. A parameter can be marked optional by appending a question mark to its name. The optional parameter should be set as the last argument in a function. The syntax to declare a function with optional parameter is as given below − function function_name (param1[:type], param2[:type], param3[:type]) Example: Optional Parameters function disp_details(id:number,name:string,mail_id?:string) { console.log(“ID:”, id); console.log(“Name”,name); if(mail_id!=undefined) console.log(“Email Id”,mail_id); } disp_details(123,”John”); disp_details(111,”mary”,”[email protected]”); The above example declares a parameterized function. Here, the third parameter, i.e., mail_id is an optional parameter. If an optional parameter is not passed a value during the function call, the parameter’s value is set to undefined. The function prints the value of mail_id only if the argument is passed a value. On compiling, it will generate following JavaScript code − //Generated by typescript 1.8.10 function disp_details(id, name, mail_id) { console.log(“ID:”, id); console.log(“Name”, name); if (mail_id != undefined) console.log(“Email Id”, mail_id); } disp_details(123, “John”); disp_details(111, “mary”, “[email protected]”); The above code will produce the following output − ID:123 Name John ID: 111 Name mary Email Id [email protected] Rest Parameters Rest parameters are similar to variable arguments in Java. Rest parameters don’t restrict the number of values that you can pass to a function. However, the values passed must all be of the same type. In other words, rest parameters act as placeholders for multiple arguments of the same type. To declare a rest parameter, the parameter name is prefixed with three periods. Any nonrest parameter should come before the rest parameter. Example: Rest Parameters function addNumbers(…nums:number[]) { var i; var sum:number = 0; for(i = 0;i<nums.length;i++) { sum = sum + nums[i]; } console.log(“sum of the numbers”,sum) } addNumbers(1,2,3) addNumbers(10,10,10,10,10) The function addNumbers() declaration, accepts a rest parameter nums. The rest parameter’s data type must be set to an array. Moreover, a function can have at the most one rest parameter. The function is invoked twice, by passing three and six values, respectively. The for loop iterates through the argument list, passed to the function and calculates their sum. On compiling, it will generate following JavaScript code − function addNumbers() { var nums = []; for (var _i = 0; _i < arguments.length; _i++) { nums[_i – 0] = arguments[_i]; } var i; var sum = 0; for (i = 0; i < nums.length; i++) { sum = sum + nums[i]; } console.log(“sum of the numbers”, sum); } addNumbers(1, 2, 3); addNumbers(10, 10, 10, 10, 10); The output of the above code is as follows − sum of numbers 6 sum of numbers 50 Default Parameters Function parameters can also be assigned values by default. However, such parameters can also be explicitly passed values. Syntax function function_name(param1[:type],param2[:type] = default_value) { } Note − A parameter cannot be declared optional and default at the same time. Example: Default parameters function calculate_discount(price:number,rate:number = 0.50) { var discount = price * rate; console.log(“Discount Amount: “,discount); } calculate_discount(1000) calculate_discount(1000,0.30) On compiling, it will generate following JavaScript code − //Generated by typescript 1.8.10 function calculate_discount(price, rate) { if (rate === void 0) { rate = 0.50; } var discount = price * rate; console.log(“Discount Amount: “, discount); } calculate_discount(1000); calculate_discount(1000, 0.30); Its output is as follows − Discount amount : 500 Discount amount : 300 The example declares the function, calculate_discount. The function has two parameters – price and rate. The value of the parameter rate is set to 0.50 by default. The program invokes the function, passing to it only the value of the parameter price. Here, the value of rate is 0.50 (default) The same function is invoked, but with two arguments. The default value of rate is overwritten and is set to the value explicitly passed. Anonymous Function Functions that are not bound to an identifier (function name) are called as anonymous functions. These functions are dynamically declared at runtime. Anonymous functions can accept inputs and return outputs, just as standard functions do. An anonymous function is usually not accessible after its initial creation. Variables can be assigned an anonymous function. Such an expression is called a function expression. Syntax var res = function( [arguments] ) { … } Example ─ A Simple Anonymous function var msg = function() { return “hello world”; } console.log(msg()) On compiling, it will generate the same code in JavaScript. It will produce the following output − hello world Example ─ Anonymous function with parameters var res = function(a:number,b:number) { return a*b; }; console.log(res(12,2)) The anonymous function returns the product of the values passed to it. On compiling, it will generate following JavaScript code − //Generated by typescript 1.8.10 var res = function (a, b) { return a * b; }; console.log(res(12, 2)); The output of the above code is as follows − 24 Function Expression and Function Declaration ─ Are they synonymous? Function expression and function declaration are not synonymous. Unlike a function expression, a function declaration is bound by the function name. The fundamental difference between the two is that, function declarations are parsed before their execution. On the other hand,
TypeScript – The Function () Constructor ”; Previous Next The Function() Constructor TypeScript supports the built-in JavaScript constructor called Function() to defined a function. The Function() constructor dynamically creates a function object at runtime. You can define your function dynamically using Function() constructor along with the new operator. The Function() constructor can accept multiple arguments. All the arguments except the last one are names of parameters and the last argument is the function body of new function to be created. Syntax Following is the syntax to define a function using Function constructor along with new operator − let res = new Function(arg1, arg2, …, functionBody); let res = Function(arg1, arg2, …, functionBody); Function() can be called with or without new. Both syntaxes will create a new Function instance. All the arguments, i.e., arg1, arg2, …, functionBody, are strings. Arguments arg1, arg2, …, – These are optional arguments treated as the names of the parameters in the function to be created. functionBody − This argument contains the statements in function definition of the new function to be created. All the arguments except the last one are optional. The last argument is required. If you are passing only a single argument, then it will be treated as function body. Notice that the Function() constructor is not passed any argument that specifies a name for the function it creates. The unnamed functions created with the Function() constructor are called anonymous functions. The new Function() is a call to the constructor which in turn creates and returns a function reference. Examples Let”s understand the Function constructor with help of some example programs in TypeScript. Example 1: Creating a simple function without parameters In the example below, the Function() constructor takes only single argument. This argument is treated as the function body. const greet = new Function(“return ”Welcome to Tutorials Point!””); console.log(greet()); On compiling TypeScript generate the same code in JavaScript. The output of the above example code is as follows − Welcome to Tutorials Point! Example 2: Creating a simple function with parameters In the example below, we call the Function() constructor passing three arguments, “x”, “y” and “return x + y”. The first two arguments are the names of the parameters of the new function instance, i.e., resFunction. const resFucntion = new Function(“x”, “y”, “return x + y”); let sum = resFucntion(5, 10); console.log(sum); On compiling, TypeScript will generate the same code in JavaScript. The compiled JavaScript code will produce the following output − 15 Example 3: Creating a function instance from a function expression In the example below, we define a function sum with function expression and pass it to the Function() constructor as a part of the parameter (function body). Here the function expression requires a return statement with the function”s name. const add = new Function( “const sum = function (a, b) {return a+ b}; return sum”, )(); console.log(add(2,3)); TypeScript compiler will generate the same code in JavaScript. The JavaScript code will produce the following output − 5 Example 4: Creating a function instance from a function declaration In the example below, we pass a function declaration as an argument to the Function constructor. The function declaration doesn’t need a return statement with the function” name. const sayHello = new Function( “return function (name) { return `Hello, ${name}` }”, )(); console.log(sayHello(“Shahid”)); On compiling, it will generate the same code in JavaScript. The output of the above example code is as follows − Hello Shahid The Function constructor in TypeScript can be used to define a function at execution time, but you should use it with caution as it can lead to vulnerabilities in the code. Print Page Previous Next Advertisements ”;
TypeScript – Overview
TypeScript – Overview ”; Previous Next JavaScript was introduced as a language for the client side. The development of Node.js has marked JavaScript as an emerging server-side technology too. However, as JavaScript code grows, it tends to get messier, making it difficult to maintain and reuse the code. Moreover, its failure to embrace the features of Object Orientation, strong type checking and compile-time error checks prevents JavaScript from succeeding at the enterprise level as a full-fledged server-side technology. TypeScript was presented to bridge this gap. What is TypeScript? By definition, “TypeScript is JavaScript for application-scale development.” TypeScript is a strongly typed, object oriented, compiled language. It was designed by Anders Hejlsberg (designer of C#) at Microsoft. TypeScript is both a language and a set of tools. TypeScript is a typed superset of JavaScript compiled to JavaScript. In other words, TypeScript is JavaScript plus some additional features. Features of TypeScript TypeScript is just JavaScript. TypeScript starts with JavaScript and ends with JavaScript. Typescript adopts the basic building blocks of your program from JavaScript. Hence, you only need to know JavaScript to use TypeScript. All TypeScript code is converted into its JavaScript equivalent for the purpose of execution. TypeScript supports other JS libraries. Compiled TypeScript can be consumed from any JavaScript code. TypeScript-generated JavaScript can reuse all of the existing JavaScript frameworks, tools, and libraries. JavaScript is TypeScript. This means that any valid .js file can be renamed to .ts and compiled with other TypeScript files. TypeScript is portable. TypeScript is portable across browsers, devices, and operating systems. It can run on any environment that JavaScript runs on. Unlike its counterparts, TypeScript doesn’t need a dedicated VM or a specific runtime environment to execute. TypeScript and ECMAScript The ECMAScript specification is a standardized specification of a scripting language. There are six editions of ECMA-262 published. Version 6 of the standard is codenamed “Harmony”. TypeScript is aligned with the ECMAScript6 specification. TypeScript adopts its basic language features from the ECMAScript5 specification, i.e., the official specification for JavaScript. TypeScript language features like Modules and class-based orientation are in line with the EcmaScript 6 specification. Additionally, TypeScript also embraces features like generics and type annotations that aren’t a part of the EcmaScript6 specification. Why Use TypeScript? TypeScript is superior to its other counterparts like CoffeeScript and Dart programming languages in a way that TypeScript is extended JavaScript. In contrast, languages like Dart, CoffeeScript are new languages in themselves and require language-specific execution environment. The benefits of TypeScript include − Compilation − JavaScript is an interpreted language. Hence, it needs to be run to test that it is valid. It means you write all the codes just to find no output, in case there is an error. Hence, you have to spend hours trying to find bugs in the code. The TypeScript transpiler provides the error-checking feature. TypeScript will compile the code and generate compilation errors, if it finds some sort of syntax errors. This helps to highlight errors before the script is run. Strong Static Typing − JavaScript is not strongly typed. TypeScript comes with an optional static typing and type inference system through the TLS (TypeScript Language Service). The type of a variable, declared with no type, may be inferred by the TLS based on its value. TypeScript supports type definitions for existing JavaScript libraries. TypeScript Definition file (with .d.ts extension) provides definition for external JavaScript libraries. Hence, TypeScript code can contain these libraries. TypeScript supports Object Oriented Programming concepts like classes, interfaces, inheritance, etc. Components of TypeScript At its heart, TypeScript has the following three components − Language − It comprises of the syntax, keywords, and type annotations. The TypeScript Compiler − The TypeScript compiler (tsc) converts the instructions written in TypeScript to its JavaScript equivalent. The TypeScript Language Service − The “Language Service” exposes an additional layer around the core compiler pipeline that are editor-like applications. The language service supports the common set of a typical editor operations like statement completions, signature help, code formatting and outlining, colorization, etc. Declaration Files When a TypeScript script gets compiled, there is an option to generate a declaration file (with the extension .d.ts) that functions as an interface to the components in the compiled JavaScript. The concept of declaration files is analogous to the concept of header files found in C/C++. The declaration files (files with .d.ts extension) provide intellisense for types, function calls, and variable support for JavaScript libraries like jQuery, MooTools, etc. Print Page Previous Next Advertisements ”;