TypeScript – Iterators and Generators

TypeScript – Iterators and Generators ”; Previous Next In TypeScript, iterators and generators allow to control the iteration over the iterables. Here, iterables are objects like arrays, tuples, etc. through which we can iterate. Using iterators and generators in the code allows us to write efficient and readable code. Here, we will discuss how to create custom iterators and generators in TypeScript. Iterators Iterators are used to traverse through the iterable objects. It is a unique function that returns the iterator object. The iterator object contains the next() method, which again returns the object having below 2 properties. value: The value property contains the value of the next element in the sequence. done: The done property contains the boolean value, representing whether the iterator reaches the end of the sequence or not. Let”s look at the below examples of iterators. Example: Using the values() Method In the code below, we have defined the ”fruits” array containing the string. The ”fruits.values()” returns an iterator object, which is stored in the ”iterator” variable. Whenever we call the next() method, it returns the object containing the ”value” and ”done” properties. You can see all the values of the array. Whenever we call the next() method 6th time, it returns the object having ”value” property with an undefined value as iterator reached to the end of the sequence. // Defining a fruits array const fruits = [”apple”, ”banana”, ”mango”, ”orange”, ”strawberry”]; // Defining an iterator const iterator = fruits.values(); // Getting the first element console.log(iterator.next().value); // apple // Getting the second element console.log(iterator.next().value); // banana // Getting remaining elements console.log(iterator.next().value); // mango console.log(iterator.next().value); // orange console.log(iterator.next().value); // strawberry console.log(iterator.next().value); // undefined On compiling, it will generate the following JavaScript code. // Defining a fruits array const fruits = [”apple”, ”banana”, ”mango”, ”orange”, ”strawberry”]; // Defining an iterator const iterator = fruits.values(); // Getting the first element console.log(iterator.next().value); // apple // Getting the second element console.log(iterator.next().value); // banana // Getting remaining elements console.log(iterator.next().value); // mango console.log(iterator.next().value); // orange console.log(iterator.next().value); // strawberry console.log(iterator.next().value); // undefined Output The output of the above example code is as follow – apple banana mango orange strawberry undefined Example: Creating the Custom Iterator Function In the code below, createArrayIterator() function is a custom iterator function. We have started with defining the ”currentIndex” variable to keep track of the index of the element in the iterable. After that, we return the object containing the ”next” property from the function. The ”next” property contains the method as a value, which returns the object containing the ”value” and ”done” property. The assigned value into the ”value” and ”done” properties is based on the current element in the sequence. After that, we used the createArrayIterator() function to traverse through the array of numbers. // Custom iterator function function createArrayIterator(array: number[]) { // Start at the beginning of the array let currentIndex = 0; // Return an object with a next method return { // next method returns an object with a value and done property next: function () { // Return the current element and increment the index return currentIndex < array.length ? { value: array[currentIndex++], done: false } : { value: null, done: true }; } }; } // Create an iterator for an array of numbers const numbers = [10, 20, 30]; const iterator = createArrayIterator(numbers); console.log(iterator.next().value); // 10 console.log(iterator.next().value); // 20 console.log(iterator.next().value); // 30 console.log(iterator.next().done); // true On compiling, it will generate the following JavaScript code. // Custom iterator function function createArrayIterator(array) { // Start at the beginning of the array let currentIndex = 0; // Return an object with a next method return { // next method returns an object with a value and done property next: function () { // Return the current element and increment the index return currentIndex < array.length ? { value: array[currentIndex++], done: false } : { value: null, done: true }; } }; } // Create an iterator for an array of numbers const numbers = [10, 20, 30]; const iterator = createArrayIterator(numbers); console.log(iterator.next().value); // 10 console.log(iterator.next().value); // 20 console.log(iterator.next().value); // 30 console.log(iterator.next().done); // true Output The output of the above example code is as follows – 10 20 30 true Generators Generator functions are also similar to the iterators, which return the values one by one rather than returning all values once. When you call the generator function, that returns the generator object which can be used to get values one by one. Generator functions are mainly useful when you want to get values one by one rather than getting all values at once and storing them in the memory. Syntax Users can follow the syntax below to create generator function in TypeScript. function* func_name() { yield val; } const gen = numberGenerator(); // “Generator { }” console.log(gen.next().value); // {value: val, done: false} In the above syntax, we have used the ”function*” to define the generator function. You can use the ”Yield” keyword to return values one by one from the generator function. When you call the generator function, it returns the generator object. When you call the next() method, it returns the object containing the ”value” and ”done” properties same as the iterator. Example: Basic Generator Function In the code below, the numberGenerator() function is a generator function. We have used the ”yield” keyword and returned 10, 20, and 30 values one by one. After that, we called the numberGenerator() function which returns the generator object. To get the values, we use the next() method of the generator object. // Basic generator function function* numberGenerator() { yield 10; yield 20; yield 30; } // Create a generator object const gen = numberGenerator(); // Call the generator function console.log(gen.next().value); // 10 console.log(gen.next().value); // 20 console.log(gen.next().value); // 30 console.log(gen.next().done); // true On compiling, it will generate the same JavaScript code. Output The output of the above example code is as follows – 10 20 30 true Example: Creating the Generator Function to Traverse a Range Here, we have defined the range()

TypeScript – Quick Guide

TypeScript – Quick Guide ”; Previous Next TypeScript – Overview 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. TypeScript – Environment Setup We already have set up TypeScript programming online, so that you can execute all the available examples online at the same time when you are doing your theory work. This gives you confidence in what you are reading and to check the result with different options. Feel free to modify any example and execute it online. var message:string = “Hello World” console.log(message) On compiling, it will generate following JavaScript code. //Generated by typescript 1.8.10 var message = “Hello World”; console.log(message); In this chapter, we will discuss how to install TypeScript on Windows platform. We will also explain how to install the Brackets IDE. You may test your scripts online by using The TypeScript at www.typescriptlang.org/Playground. The online editor shows the corresponding JavaScript emitted by the compiler. You may try the following example using Playground. var num:number = 12 console.log(num) On compiling , it will generate following JavaScript code. //Generated by typescript 1.8.10 var num = 12; console.log(num); The output of the above program is given below − 12 Local Environment Setup Typescript is an Open Source technology. It can run on any browser, any host, and any OS. You will need the following tools to write and test a Typescript program − A Text Editor The text editor helps you to write your source code. Examples of a few editors include Windows Notepad, Notepad&plus;&plus;, Emacs, vim or vi, etc. Editors used may vary with Operating Systems. The source files are typically named with the extension .ts The TypeScript Compiler

TypeScript – Mapped Types

TypeScript – Mapped Types ”; Previous Next Mapped types in TypeScript are used to create new types by transforming the properties of existing types. Mapping means creating new elements from the existing ones after making some changes. Similarly, mapped type means creating new types after making changes to the existing types. So, you can reuse the existing types to create new types. Built-in Mapped Types The built-in mapped type allows you to transform the existing types without manually transforming types. Here are the built-in mapped types available in TypeScript. Partial<T>: It creates a new type by making all properties optional of the existing type. Required<T>: It creates a new type by making all properties required of the existing type. Readonly<T>: Makes all properties optional in a new type. Record<K, T>: Creates a type with a set of properties K of type T. Useful for mapping properties of the same type. Pick<T, K>: Creates a new type by picking a set of properties K from T. Omit<T, K>: Creates a new type by omitting a set of properties K from T. Exclude<T, U>: It creates a new type by excluding all properties from T that are assignable to U. Extract<T, U>: It creates a new type by extracting all properties from T that are assignable to U. NonNullable<T>: Constructs a type by excluding null and undefined from T. Examples Let”s understand some of the commonly used built-in mapped types with help of some program examples in TypeScript. Example: Using the Partial Type In the code below, we have created the Person type containing the name and age properties. After that, we used the Partial utility type to create a new type from the Person type. The PartialPerson type has all the properties of the Person class but all are optional. We have defined the partialPerson object of the PartialPerson type, which contains only the name property as all properties are optional. // Creating the Person type type Person = { name: string; age: number; }; // Using the Partial mapped type type PartialPerson = Partial<Person>; // Creating an object of type PartialPerson const partialPerson: PartialPerson = { name: “John”, // Age is optional }; // Output console.log(partialPerson); On compiling, it will generate the following JavaScript code. // Creating an object of type PartialPerson var partialPerson = { name: “John” }; // Output console.log(partialPerson); Output { name: ”John” } Example: Using the ReadOnly Type In the code below, we used the Readonly utility type to create a new type having all properties readonly from the Person type. If we try to change any property of the partialPerson object, it will throw an error as it is readonly. // Creating the Person type type Person = { name: string; age: number; }; // Using the ReadOnly mapped type type PartialPerson = Readonly<Person>; // Creating an object of type PartialPerson const partialPerson: PartialPerson = { name: “John”, age: 30 }; // Trying to change the name property // partialPerson.name = “Doe”; // Error: Cannot assign to ”name” because it is a read-only property. // Output console.log(partialPerson); On compiling, it will generate the following JavaScript code. // Creating an object of type PartialPerson const partialPerson = { name: “John”, age: 30 }; // Trying to change the name property // partialPerson.name = “Doe”; // Error: Cannot assign to ”name” because it is a read-only property. // Output console.log(partialPerson); Output { name: ”John”, age: 30 } Example: Using the Pick Type In the code below, we have created the Animal type which contains 3 properties. After that, we used the Pick utility type to pick only name and species properties from the Animal type and create a new type named ”AnimalNameAndSpecies”. The animalNameAndSpecies object is of type AnimalNameAndSpecies, which contains only name and species properties. // Creating the Animal type type Animal = { name: string; species: string; age: number; }; // Using the Pick utility type to create a new type type AnimalNameAndSpecies = Pick<Animal, ”name” | ”species”>; // Creating an object of the AnimalNameAndSpecies type const animalNameAndSpecies: AnimalNameAndSpecies = { name: ”Milo”, species: ”Dog” }; console.log(animalNameAndSpecies); On compiling, it will generate the following JavaScript code. // Creating an object of the AnimalNameAndSpecies type const animalNameAndSpecies = { name: ”Milo”, species: ”Dog” }; console.log(animalNameAndSpecies); Output { name: ”Milo”, species: ”Dog” } Creating Custom Mapped Types Utility functions have limited functionalities. So, it is important to create the custom mapped types to map types according to your own conventions. Syntax You can follow the syntax below to create a custom-mapped type. type MyMappedType<T> = { [P in keyof T]: NewType; }; ”T” is an existing type from which we need to create a new custom-mapped type. ”P” is a property of the type. The ”keyof” operator gets each key of the type ”T”. NewType is a new type to assign to the type property ”P”. Example: Making all Properties Boolean In the code below, we created the Booleanify type which takes the type as a generic parameter. Inside the type body, we traverse each key of the type ”T” using the ”[P in keyof T]” code, and assign a boolean to it as we are changing the type of all properties to a boolean. The boolPerson object has all properties of the boolean type. // Defining the Person type type Person = { name: string; age: number; }; // Creating the custom mapped type type Booleanify<T> = { // Making all properties of Person type to Boolean [P in keyof T]: boolean; }; // Creating an object of Booleanify type const boolPerson: Booleanify<Person> = { name: true, age: true, }; console.log(boolPerson); On compiling, it will generate the following JavaScript code: // Creating an object of Booleanify type const boolPerson = { name: true, age: true, }; console.log(boolPerson); Output The above example code will produce the following output: { name: true, age: true } Example: Making all Properties Optional In this example, we are making all properties of existing types optional without using

TypeScript – Generic Classes

TypeScript – Generic Classes ”; Previous Next Generic Classes TypeScript Generic classes allow you to create a class that can work over a variety of data types rather than a single one. It increases the scalability and reusability of the code. Let”s understand how generic classes work in TypeScript. Syntax You can follow the syntax below to use the generic classes in TypeScript. class class_name<T, U> { // Class body } let obj1 = new class_name<data_type_1, data_type_2>(); In the above syntax, ”class” is a keyword to define a class. ”class_name” is a valid identifier, representing the class name. ”<T, U>” are type parameters specified in the angular bracket. You can specify as many as you want. While defining the object of the class, you need to pass data types as an argument after the class name in the angular bracket. Example In the code below, we have defined the generic class named ”Box” which takes type parameter T. In the class, we have defined the ”val” variable of type T, and the constructor function which initializes the value of the ”val” variable. After that, we defined the getters and setters named get() and set(), respectively to get the value of the ”val” variable. Next, we have defined the ”box1” and ”box2” objects of the Box class which take number and string data type as a type parameter argument, respectively. // generic class class Box<T> { // member variable val: T; // constructor with value constructor(value: T) { this.val = value; } // Method to get value get(): T { return this.val; } // Method to set value set(value: T): void { this.val = value; } } // create object of Box class let box1 = new Box<number>(10); console.log(box1.get()); // 10 let box2 = new Box<string>(“Hello”); console.log(box2.get()); // Hello On compiling, it will generate the following JavaScript code: // generic class class Box { // constructor with value constructor(value) { this.val = value; } // Method to get value get() { return this.val; } // Method to set value set(value) { this.val = value; } } // create object of Box class let box1 = new Box(10); console.log(box1.get()); // 10 let box2 = new Box(“Hello”); console.log(box2.get()); // Hello Output The output of the above code is as follows – 10 Hello Example In the TypeScript code below: We have defined the ”Stack” class which takes a type parameter ”T”. In the class, we have defined the private variable ”st” whose type is an array of type T. The constructor function initializes the ”st” array. Push() method takes the element of type ”T” as a parameter and inserts it in the ”st” array. The pop() method removes the last element from the ”st” array and returns it. The peek() method returns the last element from the array. The isEmpty() method returns a boolean value based on whether the array is empty. The size() method returns the size of the ”st” array. Next, we have defined the object of the Stack class with the number data type, performed various operations using the methods of the Stack class. // Defining the class stack class Stack<T> { // Defining the private array to store the stack elements private st: T[] = []; // Constructor to initialize the stack with initial contents constructor(initialContents?: T[]) { if (initialContents) { this.st = initialContents; } } // Method to push an element to the stack push(item: T): void { this.st.push(item); } // Method to pop an element from the stack pop(): T | undefined { return this.st.pop(); } // Method to get the top element of the stack peek(): T | undefined { return this.st[this.st.length – 1]; } // Method to check if the stack is empty isEmpty(): boolean { return this.st.length === 0; } // Method to get the size of the stack size(): number { return this.st.length; } } // Usage Example const numberStack = new Stack<number>(); numberStack.push(1); numberStack.push(2); numberStack.push(3); console.log(numberStack.peek()); // Outputs: 3 console.log(numberStack.pop()); // Outputs: 3 console.log(numberStack.peek()); // Outputs: 2 console.log(numberStack.isEmpty()); // Outputs: false console.log(numberStack.size()); // Outputs: 2 On compiling, it will generate the following JavaScript code: // Defining the class stack class Stack { // Constructor to initialize the stack with initial contents constructor(initialContents) { // Defining the private array to store the stack elements this.st = []; if (initialContents) { this.st = initialContents; } } // Method to push an element to the stack push(item) { this.st.push(item); } // Method to pop an element from the stack pop() { return this.st.pop(); } // Method to get the top element of the stack peek() { return this.st[this.st.length – 1]; } // Method to check if the stack is empty isEmpty() { return this.st.length === 0; } // Method to get the size of the stack size() { return this.st.length; } } // Usage Example const numberStack = new Stack(); numberStack.push(1); numberStack.push(2); numberStack.push(3); console.log(numberStack.peek()); // Outputs: 3 console.log(numberStack.pop()); // Outputs: 3 console.log(numberStack.peek()); // Outputs: 2 console.log(numberStack.isEmpty()); // Outputs: false console.log(numberStack.size()); // Outputs: 2 Output The output of the above code is as follows – 3 3 2 false 2 Implementing Generic Interface with Generic Classes Generic classes can also implement the generic interfaces. So, developers can use a single generic interface to implement multiple generic classes, allowing them to reuse the code. Syntax You can follow the syntax below to implement the generic interface with generic classes. class class_name<T> implements interface_name<T> { // Class body } In the above syntax, ”class class_name<T>” defines the generic class. ”implements” is a keyword to implement the interface with the class. ”interface_name<T>” is a generic interface. Example In the example below: We have defined the generic interface named ”dataBase”, which defines the findById() and save() method. Next, we have defined the generic class named ”memorydataBase”, and implemented it with the ”dataBase” interface. In the class, we have defined the ”items” map which stores the numeric value as a key, the value of type ”T”. Next, we have implemented the findById() method, which accesses the value

TypeScript – Generic Interfaces

TypeScript – Generic Interfaces ”; Previous Next Generic Interfaces In TypeScript, the generic interface is similar to the interface but it is defined with one or more type parameters. These type parameters allow the interface to be reused with different data types while still enforcing type safety and consistency. An interface in TypeScript is a way to define the structure of the object or class. It specifies the expected format which objects or classes should have, allowing to ensure consistency and type safety in the code. Syntax You can follow the syntax below to define the generic interfaces. interface IGeneric<T> { value1: T; value2: T; } In the above syntax, ”IGeneric” is a typed interface, which accepts the custom data type. In the interface, we have used the type ”T” as a value of the value1 and value2 properties. Example In the code below, we have created the ”IGeneric” interface with the custom type ”T”. It has value1 and value2 properties of type ”T”. Next, we have defined the ”obj” object of the IGeneric interface type and used the number data type as a generic type with the interface. After that, we print the value of the ”value1” property of the object in the output. // Generic interface interface IGeneric<T> { value1: T; value2: T; } // Object of generic interface let obj: IGeneric<number> = { value1: 10, value2: 20 }; console.log(obj.value1); On compiling, it will generate the following JavaScript code: // Object of generic interface let obj = { value1: 10, value2: 20 }; console.log(obj.value1); Output The output of the above example code is as follows – 10 Example In this code, we use the ”T” and ”U” both data types with the ”IGeneric” interface. The value1 property is of type ”T” and the value2 property is of type ”U” in the interface. Next, we have defined the ”obj” object of interface type with number and string custom data types. // Generic interface interface IGeneric<T, U> { value1: T; value2: U; } // Define object with a generic interface let obj: IGeneric<number, string> = { value1: 10, value2: “Hello” }; console.log(obj.value2); On compiling, it will generate the following JavaScript code: // Define object with a generic interface let obj = { value1: 10, value2: “Hello” }; console.log(obj.value2); Output The output of the above example code is as follows – Hello Example The below example is very similar to the previous one, but the ”IGeneric” interface contains the merge() method which takes the parameters of type ”U” and returns the value of type ”U”. While defining the ”obj” object, we used the number and string data types with the interface. It means the merge() method will take two string parameters, and return a string value. In the output, the code prints the concatenated string, which we have passed as parameters of the merge() method. // Generic interface interface IGeneric<T, U> { value1: T; // method that returns the value of type U merge: (a: U, b: U) => U; } // Define object with a generic interface let obj: IGeneric<number, string> = { value1: 10, merge: (a, b) => a + b }; console.log(obj.merge(“Hello”, “world!”)); // Hello world! On compiling, it will generate the following JavaScript code: // Define object with a generic interface let obj = { value1: 10, merge: (a, b) => a + b }; console.log(obj.merge(“Hello”, “world!”)); // Hello world! Output Helloworld! Generic Interface as a Function Type Developers can also use the generic interface as a function type. This enables you to use the same function interface across diverse types and scenarios, ensuring type safety without sacrificing flexibility. Example In the code below, ”func_interface” accepts the generic types T and U. It defines the structure for the function, which takes the parameter of type ”T” and returns the value of type ”U”. Next, we have defined the function expression which returns the string length and stored it in the ”stringToLength” variable. The type of the function expression is defined using the generic interface with string and number data types. Similarly, we have defined another function that converts a number to a string, and its type is func_interface with string and number data type. Next, we invoke the functions and print their output in the console. // Define a generic interface for a function interface func_interface<T, U> { (input: T): U; } // A specific function that matches the func_interface interface const stringToLength: func_interface<string, number> = (input) => { return input.length; }; // Using the function const result = stringToLength(“Hello, TypeScript!”); // returns 18 console.log(result); // Another function that matches the func_interface interface const numberToString: func_interface<number, string> = (input) => { return `Number: ${input}`; }; // Using the second function const output = numberToString(123); // returns “Number: 123” console.log(output); On compiling, it will generate the following JavaScript code: // A specific function that matches the func_interface interface const stringToLength = (input) => { return input.length; }; // Using the function const result = stringToLength(“Hello, TypeScript!”); // returns 18 console.log(result); // Another function that matches the func_interface interface const numberToString = (input) => { return `Number: ${input}`; }; // Using the second function const output = numberToString(123); // returns “Number: 123″ console.log(output); Output 18 Number: 123 In short, generic interfaces allow developers to reuse the interfaces with multiple data types. Generic interfaces can be used as an object or function type, allowing to reuse the single function or object with different structures. Print Page Previous Next Advertisements ”;

TypeScript – Date Object

TypeScript – Date Object ”; Previous Next In TypeScript, the ”Date” object is a built-in object that allows developers to create and manage dates and times. It is directly inherited from JavaScript, so it contains the same methods as the Date object in JavaScript. However, you need to ensure that typing of the Date object and return value from the Date methods in TypeScript. Syntax You can follow the syntax below to use the Date object in TypeScript. let date: Date = new Date(); // Date Constructor // OR date = new Date(milliseconds); // Passes milliseconds // OR date = new Date(date_String); // Passes date string // OR date = new Date(year, month, day, hour, minute, second, milli_second); In the above syntax, we have explained 4 different ways to use the Date() constructor which takes different parameters. Parameters milliseconds: It is the total number of milliseconds since 1st January, 1971. date_String: It is a date string containing year, month, day, etc. year, month, day, hour, minute, second, milli_second: The Date() constructor creates a new date based on these parameters. Return Value The Date constructor returns the Date string based on the parameters passed. If we don”t pass any parameters, it returns the date string with the current time. Examples Let”s understand more about the date object with the help of some example in TypeScript. Example: Creating New Dates In the code below, first, we have created using the Date() constructor and without passing any parameters. It returns the current date and time. Next, we have passed the milliSeconds as a parameter, and it returns the date according to the total milliseconds. Next, we have passed the date in the string format as a parameter of the Date() constructor, and it returns a new date according to the date string. Next, we have passed year, month, day, etc. as a separate parameter of the Date() constructor, which creates a new date string using the parameters. let date: Date = new Date(); // Date Constructor console.log(date); // Output: Current Date and Time date = new Date(10000000000); // Passes milliseconds console.log(date); // Output: 1970-04-26T17:46:40.000Z date = new Date(”2020-12-24T10:33:30”); // Passes date string console.log(date); // Output: 2020-12-24T10:33:30.000Z date = new Date(2020, 11, 24, 10, 33, 30, 0); // Passes year, month, day, hour, minute, second, millisecond console.log(date); // Output: 2020-12-24T10:33:30.000Z On compiling, it will generate the following JavaScript code. let date = new Date(); // Date Constructor console.log(date); // Output: Current Date and Time date = new Date(10000000000); // Passes milliseconds console.log(date); // Output: 1970-04-26T17:46:40.000Z date = new Date(”2020-12-24T10:33:30”); // Passes date string console.log(date); // Output: 2020-12-24T10:33:30.000Z date = new Date(2020, 11, 24, 10, 33, 30, 0); // Passes year, month, day, hour, minute, second, millisecond console.log(date); // Output: 2020-12-24T10:33:30.000Z Output The output of the above example code will show the current date and provided custom dates. Example: Accessing Date and Time Components You can use the getFullYear() method to get the year from the date string. Similarly, the getMonth() and getDate() methods are used to get the month and day from the date string, respectively. let someDate = new Date(); console.log(`Year: ${someDate.getFullYear()}`); // Outputs current year console.log(`Month: ${someDate.getMonth()}`); // Outputs current month (0-indexed) console.log(`Day: ${someDate.getDate()}`); // Outputs current day On compiling, it will generate the same JavaScript code. let someDate = new Date(); console.log(`Year: ${someDate.getFullYear()}`); // Outputs current year console.log(`Month: ${someDate.getMonth()}`); // Outputs current month (0-indexed) console.log(`Day: ${someDate.getDate()}`); // Outputs current day Output The output of the above example code will show the year, month and day of the current date. Example: Adding Days to the Current Date We can use different methods to manipulate the date string. Here, we have used the setDate() method to increment the days by 7 in the date string. The getDate() method returns the date and we add 7 to that. After that, the new day we pass it to the parameter of the setDate() method. The setDate() method automatically manages the changing the changing month or year. For example, if the current date is 30 and you want to add 7 days to that, it returns the new date with the next month. let date = new Date(); date.setDate(date.getDate() + 7); // Adds 7 days to the current date console.log(date); // Outputs the date 7 days in the future On compiling, it will generate the same JavaScript code. let date = new Date(); date.setDate(date.getDate() + 7); // Adds 7 days to the current date console.log(date); // Outputs the date 7 days in the future Output Its output will show the date seven days ahead of the current date. Example: Formatting a Date We can use the different options to format the date string. Here, we have used the DateTimeFormatOptions() method to format the date string. It takes the ”en-US” as a first parameter, which is a country code, and the options object as a second parameter. The options object contains the format details for the weekday, year, month, and day. let today = new Date(); let options: Intl.DateTimeFormatOptions = { weekday: ”long”, year: ”numeric”, month: ”long”, day: ”numeric” }; let formattedDate = new Intl.DateTimeFormat(”en-US”, options).format(today); console.log(formattedDate); // E.g., ”Tuesday, April 27, 2024” On compiling, it will generate the following JavaScript code. let today = new Date(); let options = { weekday: ”long”, year: ”numeric”, month: ”long”, day: ”numeric” }; let formattedDate = new Intl.DateTimeFormat(”en-US”, options).format(today); console.log(formattedDate); // E.g., ”Tuesday, April 27, 2024” Output The output of the above example code will produce the today”s date formatted in US format. Example: Handling Time Zones Here, we are handling different time zones in the code below. First, we have created the date according to the UTC using the UTC() method of the Date object and passed it as a parameter of the Date() constructor. Next, we used the toLocaleString() method to change the date string according to the timezone. The toLocaleString() method takes the country code as a first parameter, and the object with the timeZone property as a second parameter. let utcDate =

TypeScript – Type Assertions

TypeScript – Type Assertions ”; Previous Next Type assertion is a mechanism in TypeScript that informs the compiler of the variable type. We can override the type using a type assertion if TypeScript finds that the assignment is wrong. We must be certain that we are correct since the assignment is always legitimate when we employ a type assertion. If not, our program might not operate properly. Type assertion functions similarly to typecasting, but unlike C# and Java, it does not do type verification or data rearrangement. Runtime support is provided for typecasting, although type assertion does not affect runtime. Type assertions are solely a compile-time construct to give the compiler indications about how we want our code to be inspected. How to Perform Type Assertions? Type assertion is a Typescript technique that tells the compiler about the type of variable. Though type assertion doesn’t recreate code, typecasting does. You can tell the compiler not to infer the type of a value by using type assertion. We utilize Type assertion to convert a variable from one type to another, such as any to a number. To do type assertion, we can either use the “<>” operator or the “as” operator. Typecasting provides runtime support, whereas type assertion has no impact on runtime. There are three techniques to perform Type Assertion in TypeScript, and those are: Using as operator Using <> operator Using object Using as Operator for Type Assertion The as keyword in TypeScript offers a method for displaying Type Assertion. Syntax let variable_any: any = 123 let variable_number: number = variable_any as number In the above syntax, we used the “as” keyword on any type variable for type assertion. Example let variable_unknown: unknown = “Tutorialspoint”; console.log(“variable_unknown value is: “, variable_unknown); let variable_number: number = (variable_unknown as string).length; console.log(“Length of variable_unknown: “, variable_number); On compiling, it will generate the following JavaScript code: var variable_unknown = “Tutorialspoint”; console.log(“variable_unknown value is: “, variable_unknown); var variable_number = variable_unknown.length; console.log(“Length of variable_unknown: “, variable_number); The output will be: variable_unknown value is: Tutorialspoint Length of variable_unknown: 14 Using <> Operator for Type Assertion The <> operator is another way to perform type assertion in TypeScript. Syntax let variable_any: any = 123 let variable_number: number = <number> variable_any In the above syntax, we used the “<>” operator on any type variable for type assertion. Example let my_number: unknown = 12345 console.log(”my_number value is: ”, my_number) let num: number = <number>my_number console.log(”typeof num is: ”, typeof num) On compiling, it will generate the following JavaScript code: var my_number = 12345; console.log(”my_number value is: ”, my_number); var num = my_number; console.log(”typeof num is: ”, typeof num); The output will be: my_number value is: 12345 typeof num is: number Using Object for Type Assertion Objects are another way to perform the type assertion, unlike the “as” and “<>” operators; the objects can use for multiple type assertions at once. Syntax interface info { name: string, value: string } let my_obj = <info> { name: ”ABC”, value: ”abc”} In the above syntax, we used the object to perform type assertion. Example interface info { name: string value: string } let my_obj = <info>{} my_obj.name = ”Tutorialspoint” my_obj.value = ”typescript” console.log(my_obj) On compiling, it will generate the following JavaScript code: var my_obj = {}; my_obj.name = ”Tutorialspoint”; my_obj.value = ”typescript”; console.log(my_obj); The output will be: { name: ”Tutorialspoint”, value: ”typescript” } Print Page Previous Next Advertisements ”;

TypeScript – Typeof Type Operator

TypeScript – Typeof Type Operator ”; Previous Next In TypeScript, the typeof is one of the most helpful operators and keywords to check the types of variables or identifiers. However, TypeScript is a type-strict language. So, we need to define the type of the variable or object while defining the identifier itself. Still, sometimes we need to check the type of the variable. For example, we are taking the data from the user via forms and handling it via TypeScript. Then we have to validate the data and perform some database operations. Also, the identifier can have multiple types in TypeScript. So, using the typeof operator, we can check the identifier type after initializing it. Syntax The below syntax demonstrates the use of typeof operator with the identifiers. let type = typeof <variable> Where, variable − is an identifier, for which we need to check the type. Return Value It returns a string according to the data type of the operand of the typeof operator. Examples Let”s understand the typeof operator with the help of examples in TypeScript − Example 1 In this example, we have used the typeof operator with the string, number, boolean, and undefined variables. Also, we used the typeof operator with the variable containing the null as a value. In the output, we can see that It returns the string representing the type of the identifier. For the null_value1 identifier, the typeof operator returns the object. // Defining the variables of particular type and checking its type. let str1: string = “TutorialsPoint”; console.log(typeof str1); let num1: number = 32; console.log(typeof num1); let bool1: boolean = true; console.log(typeof bool1); let un_defined; console.log(typeof un_defined); let null_value1 = null; console.log(typeof null_value1); On compiling, it will generate the following JavaScript code − // Defining the variables of particular type and checking its type. var str1 = “TutorialsPoint”; console.log(typeof str1); var num1 = 32; console.log(typeof num1); var bool1 = true; console.log(typeof bool1); var un_defined; console.log(typeof un_defined); var null_value1 = null; console.log(typeof null_value1); Output The above code will produce the following output − string number boolean undefined object Example 2 In the example below, we have created the objection containing some key-value pairs, a function returning the number value, and an array of numbers that contains different values. Also, we used the typeof operator to check the type of all. The typeof operator returns the “object” string for the object, the “function” string for the Function, and the “object” string for the array, as the array is the instance of the object. // using the typeof operator with object, function, and array. let demo_obj = { prop: “value”, }; console.log(typeof demo_obj); function func() { let a = 10 + 20; return a; } console.log(typeof func); let array: Array<number> = [4, 23, 212, 2123, 323, 3]; console.log(typeof array); On compiling, it will generate the following JavaScript code − // using the typeof operator with object, function, and array. var demo_obj = { prop: “value” }; console.log(typeof demo_obj); function func() { var a = 10 + 20; return a; } console.log(typeof func); var array = [4, 23, 212, 2123, 323, 3]; console.log(typeof array); Output The above code will produce the following output − object function object Example 3 In this example, we checked the type of the NaN keyword using the typeof operator, which returns the “number” string. The type of negative Infinity is also a number. The PI is the property of the Math class, which contains the number value. That’s why the typeof operator returns “number” for the Math.PI property. The pow() is the Math library function to get the power of any numbers. So, the typeof operator returns the “function” for the Math.pow() method. // using the typeof operator with NaN, infinity, library methods, and members. let NaN_type = NaN; console.log(typeof NaN_type); let infi = -Infinity; console.log(typeof infi); let pI = Math.PI; console.log(typeof pI); let pow = Math.pow; console.log(typeof pow); On compiling, it will generate the following JavaScript code − // using the typeof operator with NaN, infinity, library methods, and members. var NaN_type = NaN; console.log(typeof NaN_type); var infi = -Infinity; console.log(typeof infi); var pI = Math.PI; console.log(typeof pI); var pow = Math.pow; console.log(typeof pow); Output The above code will produce the following output − number number number function Example 4 In this example, we used the typeof operator to get the type of variable1 and defined variable2 of the same type as variable1. Also, we used the type alias to store the type of variable3. The type named type1 contains the type of variable3, which is a string. After that, we used type1 to define the type of variable4. In the output, users can observe that the type of variable4 is the same as variable3. // defining the variable1 of type number var variable1: number = 10; // To define the variable2 as of same type variable1 let variable2: typeof variable1 = 20; console.log(typeof variable2); // variable3 of string type var variable3: string = “Hello!”; // using the type alias to define the type of same type as variable3 type type1 = typeof variable3; // defining the variable4 of type named type1 let variable4: type1 = “Hi”; console.log(typeof variable4); On compiling, it will generate the following JavaScript code − // defining the variable1 of type number var variable1 = 10; // To define the variable2 as of same type variable1 var variable2 = 20; console.log(typeof variable2); // variable3 of string type var variable3 = “Hello!”; // defining the variable4 of type named type1 var variable4 = “Hi”; console.log(typeof variable4); Output The above code will produce the following output − number string Print Page Previous Next Advertisements ”;

TypeScript – Type Guards

TypeScript – Type Guards ”; Previous Next In TypeScript, the type guards are used to determine a variable”s type, often inside a conditional or functional block. The type guards usually take the variable and return a Boolean value or the variable type. Type guards allow you to tell the TypeScript compiler to infer a given type for a variable in a specific context, guaranteeing that an argument”s type is what you say it is. Similar to feature detection, type guards are commonly used to narrow down a type, enabling you to identify the appropriate prototypes, methods, and attributes of a value. As a result, handling that value become simple for the user. The user-defined type guards can be created in TypeScript, but it also has built-in operators like the ”typeof”, ”in”, and the ”instanceof” operator. The ”typeof” type guard in TypeScript In TypeScript, the ”typeof” operator is used to get the type of the variable. According to the variable”s type, it returns the values like − Number String Boolean Object Bigint Symbol Function Undefined Syntax Users can follow the below syntax to use the ”typeof” type, guard operator. typeof variable_name In the above syntax, we use the typeof operator just before the variable name to get the variable type. Example In the following example, we will use the ”typeof” type guard in TypeScript. We have declared four variables of types” number”, ”string”, ”boolean”, and ”object”. After that, we console log their variable type using the ”typeof” operator of the TypeScript. let my_number: number = 123 let my_string: string = ”Tutorialspoint” let my_boolean: boolean = true let my_object: { id: number } = { id: 1 } console.log(”type of my_number variable is: ” + typeof my_number) console.log(”type of my_string variable is: ” + typeof my_string) console.log(”type of my_boolean variable is: ” + typeof my_boolean) console.log(”type of my_object variable is: ” + typeof my_object) On compiling, it will generate the following JavaScript code − var my_number = 123; var my_string = ”Tutorialspoint”; var my_boolean = true; var my_object = { id: 1 }; console.log(”type of my_number variable is: ” + typeof my_number); console.log(”type of my_string variable is: ” + typeof my_string); console.log(”type of my_boolean variable is: ” + typeof my_boolean); console.log(”type of my_object variable is: ” + typeof my_object); Output The above code will produce the following output − type of my_number variable is: number type of my_string variable is: string type of my_boolean variable is: boolean type of my_object variable is: object In the above output, users can see the output of the ”typeof” operator for four variables: ”number”, ”string”, ”boolean”, and ”object”. The ”in” type guard in TypeScript The ”in” type guard determines if an object contains a specific attribute, which is then used to distinguish between distinct types. It typically returns a boolean, indicating if the property is present in the object. It is utilized for its narrowing characteristics. Syntax Users can follow the below syntax to use the ”in” type guard operator. property_name in object_name In the above syntax, we use the ”in” operator to find whether the property exists in the object. Example In the following example, we will use the ”in” type guard in TypeScript. We have declared three objects that consist of different properties. We use the” in” type guard to check whether a required property exists in the object. We can even check if a property contains another property or if it is not using it. In the ”obj3”, we check if an object”s property contains another property or not. let obj1: { id: number; name: string } = { id: 1, name: ”Tutorialspoint” } let obj2: { name: string; roll: number } = { name: ”XYZ”, roll: 12 } let obj3: { id: number; marks: { english: number; math: number } } = { id: 101, marks: { math: 90, english: 80, }, } console.log(”Is name in obj1? => ” + (”name” in obj1)) console.log(”Is id obj2? => ” + (”id” in obj2)) console.log(”Is marks in obj3? => ” + (”marks” in obj3)) console.log(”Is math in obj3.marks? => ” + (”math” in obj3.marks)) On compiling, it will generate the following JavaScript code − var obj1 = { id: 1, name: ”Tutorialspoint” }; var obj2 = { name: ”XYZ”, roll: 12 }; var obj3 = { id: 101, marks: { math: 90, english: 80 } }; console.log(”Is name in obj1? => ” + (”name” in obj1)); console.log(”Is id in obj2? => ” + (”id” in obj2)); console.log(”Is marks in obj3? => ” + (”marks” in obj3)); console.log(”Is math in obj3.marks? => ” + (”math” in obj3.marks)); Output The above code will produce the following output − Is name in obj1? => true Is id in obj2? => false Is marks in obj3? => true Is math in obj3.marks? => true In the above output, users can see the output of the ”in” operator in different circumstances in our code. The ”instanceof” type guard in TypeScript The ”instanceof” is a built-in type guard used to determine whether a value is an instance of a specific constructor function or class. We may use this type-guard to determine the type of instance type by testing if an object or value is derived from a class. Syntax Users can follow the below syntax to use the ”instanceof” type-guard operator. object_name instanceof class_name In the above syntax, we use the ”instanceof” operator to find whether the object is an instance of the class. Example In the following example, we will use the ”instanceof” type guard in TypeScript. We have declared a ”Parent” class and a child classe, ”Child”. We declare an objects of the ”Child” class and use the ”instanceof” operator to find the object belongs to which class. class Parent { id: number constructor(id: number) { this.id = id } } class Child extends Parent { id: number name: string constructor(id: number, name: string) { super(id) this.name = name } } let child = new Child(101, ”ABC”) console.log(”child instanceof Child => ” + (child

TypeScript – Indexed Access Types

TypeScript – Indexed Access Types ”; Previous Next In TypeScript, Indexed access types are also known as lookup types. It is used to access the type of property of another type. It is a powerful way and helpful to access the type properties of the complex type structure. This feature allows you to use the type system more effectively, ensuring type safety in scenarios involving property access and manipulation. Syntax You can follow the syntax below to use the index access types in TypeScript. type new_type = existing_type[key]; In the above syntax, ”type” is a keyword to define a new type. ”existing_type” is an existing type. The ”key” is a property of the existing_type whose type we need to get. Examples Let”s understand the indexed access types with the help of some examples in TypeScript. Example: Accessing Object Property Types Indexed access types are very useful when you need to get the type of the specific property of the existing type. In the code below, we have defined the User type which contains the id, and age properties of the number type and name property of the string type. The User[”name”] is used to access the type of the ”name” property of the User type, which is a string. Next, we have defined the userName variable whose type is ”UserNameType” (string). If you try to assign a number to the userName variable, it will throw an error. type User = { id: number; name: string; age: number; }; // Access the type of ”name” property from User type UserNameType = User[”name”]; // type is string let userName: UserNameType; userName = “Alice”; // Ok console.log(userName); // Alice // userName = 123; // Error: Type ”number” is not assignable to type ”string”. On compiling, it will generate the following JavaScript code. let userName; userName = “Alice”; // Ok console.log(userName); // Alice // userName = 123; // Error: Type ”number” is not assignable to type ”string”. Output Alice Example: Accessing Nested Object Property Types Indexed access types are more useful when you need to get the type of any property of the complex type structure. In the code below, the ”Product” type has id and details properties. The details property is a nested type containing the name and price properties. We used the Product[”details”][”price”] to access the type of the ”price” property of the ”details” property, which is a number. type Product = { id: number; details: { name: string; price: number; }; }; // Access the type of the nested ”price” property type ProductPriceType = Product[”details”][”price”]; // type is number let price: ProductPriceType; price = 19.99; // Correct usage console.log(price); // Output: 19.99 // price = “20.00”; // Error: Type ”string” is not assignable to type ”number”. On compiling, it will generate the following JavaScript code. let price; price = 19.99; // Correct usage console.log(price); // Output: 19.99 // price = “20.00”; // Error: Type ”string” is not assignable to type ”number”. Output 19.99 Example: Using the keyof operator with indexed access types This example is similar to the first example. Here, we have used the ”keyof” operator to access all keys of the User type. When you use the Keyof operator with the type and use it as an index value, it gets the union of type of all properties of the object. Here, ”keyof User” gives us the number | string, which is a type of all properties of the User type. type User = { id: number; name: string; age: number; }; // Access the type of ”name” property from User type UserNameType = User[keyof User]; // type is number | string let userName: UserNameType; userName = “Hello”; // Correct usage console.log(userName); // Output: Hello userName = 123; // Correct usage console.log(userName); // Output: 123 On compiling, it will generate the following JavaScript code. let userName; userName = “Hello”; // Correct usage console.log(userName); // Output: Hello userName = 123; // Correct usage console.log(userName); // Output: 123 Output Hello 123 Example: Indexed Access with Arrays When you want to access the type of the array elements, you can use the ”number” as an index. In the code below, we have defined the StringArray type, which contains the array of the string. The ”StringArray[number]” gets the type of the array element, which is a string. type StringArray = string[]; // Access the type of an array element type ElementType = StringArray[number]; // type is string let element: ElementType; element = “Hello”; // Correct usage console.log(element); // element = 123; // Error: Type ”number” is not assignable to type ”string”. On compiling, it will generate the following JavaScript code. let element; element = “Hello”; // Correct usage console.log(element); // element = 123; // Error: Type ”number” is not assignable to type ”string”. Output Hello This way you can access the type of the properties of the existing types using the indexed access type. You can also use the ”number” property to access the type of the array elements. Print Page Previous Next Advertisements ”;