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 ”;
Category: typescript
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 ”;
TypeScript – Any
TypeScript – Any Type ”; Previous Next The any type in TypeScript is a specific type that can represent any value. It is generally used when a type of variable is unknown or not yet defined. The any type is useful when converting the JavaScript code to TypeScript. Any type is not a type in traditional sense. It is like a placeholder that tells the TypeScript compiler to ignore type checking for the particular variable, function, etc. Can represent any value A variable declared with any type can hold value of any datatype – let x: any; x = “Hello”; x = 23; x = true; Here the variable x is declared with any type. This allows us to assign any value, string, number, boolean, etc. to the variable. The type of a variable of any type is undefined when you check using typeof operator – let x: any; console.log(typeof x) // undefined On compiling, it will generate the following JavaScript code – let x; console.log(typeof x); // undefined The output of the above example code is as follows – undefined Example Let”s understand the any type with help of the below TypeScript example – let x: any; console.log(typeof x); x = “Hello”; console.log(typeof x); x = 23; console.log(typeof x); x = true; console.log(typeof x); Here the variable is declared of any type. Then assigned this with values of different types (string, number and boolean). On compiling, it will generate the following JavaScript code – let x; console.log(typeof x); x = “Hello”; console.log(typeof x); x = 23; console.log(typeof x); x = true; console.log(typeof x); The output of the above example code is as follows – undefined string number boolean Function Parameters of any Type You can also define a function with parameter of any type – function func(para: any){ } Here the function func can take parameter of any type – number, string, boolean, etc. Example Let”s take an example, function greet(name: any): string{ return `Hello Mr. ${name}`; } console.log(greet(”Shahid”)); console.log(greet(123)); The function greet() is defined with a parameter of any type. So it can accept an argument of any type (number, string, etc.). We have called the greet() function passing two different values of string and number types. You can notice that it works for both types of the arguments. On compiling, the above typescript code will generate the following JavaScript code – function greet(name) { return `Hello Mr. ${name}`; } console.log(greet(”Shahid”)); console.log(greet(123)); The output of the above example code is as follows – Hello Mr. Shahid Hello Mr. 123 Object of any Type An object can also be defined of any type. Such object can have the properties of any type. Let’s take an example – const student: any = { name: “John Doe”, age: 32, isEnrolled: true, } Here the student object declared with any. It consists of three properties of different types. Example Try the following example, const student: any = { name: “John Doe”, age: 32, isEnrolled: true, } console.log(student.name); console.log(student.age); console.log(student.isEnrolled); On compiling, it will generate the following JavaScript code – const student = { name: “John Doe”, age: 32, isEnrolled: true, }; console.log(student.name); console.log(student.age); console.log(student.isEnrolled); The output of the above example code is as follows – John Doe 32 true Why to use any Type? One reason to use any type is when you are working with the code that are not type-checked. For example, if you are using preexisting JavaScript code, the any type is useful in converting the JavaScript code to TypeScript. If you are using a third party library that is not written in TypeScript, you may need to use any type for the variable in TypeScript code. Another reason to use the any type is when you are not sure what will be the type of a value. For example, a function accepting user input can be defined with any type to handle any type of data from users. Any type is discouraged to use in new TypeScript code. It is advised to be careful when using the any type. If you use any type too often, you code will become less type safe. Type Assertion Use type assertion to narrow down the type of any variable – let value: any = “hello world”; let lenStr: number = (value as string).length; console.log(lenStr); In the above code, variable value is defined of any type. Then it is narrowed down to string. On compiling, it will generate the following JavaScript code – let value = “hello world”; let lenStr = value.length; console.log(lenStr); The output of the above code is as follows – 11 Caution Any type can lead to error if not used with caution. In the below example, we are trying to access the property enrYear that doesn”t exist. This will cause a runtime error because we have defined student object with any. Notice it doesn”t show a compile time error. const student: any = { name: “John Doe”, age: 32, isEnrolled: true, } console.log(student.name); console.log(student.age); console.log(student.enrYear); On compilation, it will generate the following JavaScript code – const student = { name: “John Doe”, age: 32, isEnrolled: true, }; console.log(student.name); console.log(student.age); console.log(student.enrYear); The output of the above example code is as follows – John Doe 32 undefined Any vs. unknown When a variable is declared with any type and you can access its non-existing property. Example: Variable declared with any let user: any; user.isEnrolled; The above TypeScript code will not show any error at compilation. But it will through the following run time error. Cannot read properties of undefined (reading ”isEnrolled”) Example: Variable declared with unknown let user:unknown; user.isEnrolled; The above code will show a compile time error as follows – ”user” is of type ”unknown”. Print Page Previous Next Advertisements ”;
TypeScript – Do While Loop
TypeScript – doâ¦while loop ”; Previous Next The doâ¦while loop is similar to the while loop except that the do…while loop doesnât evaluate the condition for the first time the loop executes. However, the condition is evaluated for the subsequent iterations. In other words, the code block will be executed at least once in a doâ¦while loop. Syntax The syntax of do…while loop in TypeScript is as follows â do { //statements } while(condition) In the syntax of do…while loop, do block contains the code block that is executed in each iteration. The while block contains the condition that is checked after the do block executes. In the above syntax, the condition is a boolean expression that evaluates to either true or false. Flowchart The flowchart of the do…while loop looks as follows â The flowchart shows that at first the loop control goes to the code block. Once the code block is executed, the condition is checked. If the condition evaluates to true, the loop control again goes to the code block and code block is executed. If the condition evaluates to false, the do…while loop breaks. Letâs now try an example of do…while loop in TypeScript. Example: doâ¦while In the example below, we define a variable n with value 10. Inside the do block, we print the value of n and then decrement it. The while block holds the condition n>=0, which determines if another iteration occurs. var n:number = 10; do { console.log(n); n–; } while(n>=0); On compiling, it will generate following JavaScript code − var n = 10; do { console.log(n); n–; } while (n >= 0); The example prints numbers from 0 to 10 in the reverse order. 10 9 8 7 6 5 4 3 2 1 0 typescript_loops.htm Print Page Previous Next Advertisements ”;
TypeScript – While Loop
TypeScript – While Loop ”; Previous Next The while loop executes the instructions each time the condition specified evaluates to true. In other words, the loop evaluates the condition before the block of code is executed. As a superset of JavaScript, TypeScript inherits and expands upon JavaScript’s features including different types of loops. The while loop is an entry-controlled loop. In an entry-controlled loop, the condition is checked first and if the condition is true then the statements within the loop body are executed. While in an exit-controlled loop, the condition is checked after executing the loop body. The do…while loop is an example of the exit-controlled loop. Syntax The syntax of the while loop in TypeScript is as follows – while(condition) { // statements if the condition is true } Flow Diagram The flow diagram of the while loop looks as follows – Here is a breakdown of the while loop”s behavior – Condition evaluation − the while loop evaluates the condition before each iteration. Execution − if the condition evaluates to true, the code block within the loop body is executed. Iteration − After code block execution is finished, the loop jumps back to the first step (condition evaluation) to check if another iteration is required. Example: While loop var num:number = 5; var factorial:number = 1; while(num >=1) { factorial = factorial * num; num–; } console.log(“The factorial is “+factorial); The above code snippet uses a while loop to calculate the factorial of the value in the variable num. On compiling, it will generate the following JavaScript code − var num = 5; var factorial = 1; while (num >= 1) { factorial = factorial * num; num–; } console.log(“The factorial is ” + factorial); It produces the following output − The factorial is 120 While loop with a break statement You can use a combination of an if statement and a break statement to terminate a while loop prematurely. The if statement checks a condition. If the condition evaluates to true, the break statement forces the while loop to exit, skipping any remaining code within the loop body. Example In the following example, the loop iterates until i reaches to 3. When the value of i becomes 3, the condition (i === 3) is true and break statement terminates the loop. var i: number = 0; while (i < 5) { if (i === 3) { break; } console.log(i); i++; } On compiling, it will generate the following JavaScript code. var i = 0; while (i < 5) { if (i === 3) { break; } console.log(i); i++; } The output of the above example code is as follows – 0 1 2 While loop vs. for loop You should use a for loop when the number of iterations is fixed and known. When the number of iterations is not known, you should use the while loop. We can convert a for loop to the while loop by omitting the first and last expression in the for loop. Let’s take the example of the following for loop – for (var i = 0; i < 5; i++){ console.log(i) } The output is as follows- 0 1 2 3 4 We can modify the above example code as follows – var i = 0 for ( ; i < 5; ){ console.log(i); i++; } It will also produce the same output as the above code – 0 1 2 3 4 In the above example, we omitted the first and third expressions in the for loop. It is similar to the while loop statement. var i = 0 while(i < 5){ console.log(i); i++; } It will also produce the same output as the above two examples. 0 1 2 3 4 Notice that a for loop without first and third expressions is similar to the while loop. Print Page Previous Next Advertisements ”;
TypeScript – Literal Types
TypeScript – Literal Types ”; Previous Next In TypeScript, literal types are subtypes of the primitive data types. The literal types allow you to specify the exact value the variable can contain. There are three types of the literal types in TypeScript. String literal types Numeric literal types Boolean literal types Each of them allows you to store the specific value in the variable rather than storing the generalized string, numeric, or boolean value. Syntax You can follow the syntax below to use the literal types in TypeScript. type lit_type = type_1 | type_2 | type_3 | … In the above syntax, ”type” is a keyword to create a type alias. The ”lit_type” is the name of the type. The ”type_1”, ”type_2”, and “type_3” are values of type string, Boolean, or number. String Literal Types The string literal type allows you to define a set of specific values from which a variable or function parameter should contain any value. Example In the code below, we have created the ”Direction” type which contains all 4 directions in string format. The type of the move() function parameter is Direction so it accepts any value from the 4 directions. If you try to pass any value other than 4 directions as an argument, it throws an error. // Defining a custom-type Direction type Direction = “North” | “East” | “South” | “West”; // Defining a function move that takes a single argument of type Direction. function move(direction: Direction) { console.log(`Moving in the direction: ${direction}`); } move(“North”); move(“East”); // move(“Northeast”); // Error: Argument of type ””Northeast”” is not assignable to parameter of type ”Direction”. On compiling, it will generate the following JavaScript code. // Defining a function move that takes a single argument of type Direction. function move(direction) { console.log(`Moving in the direction: ${direction}`); } move(“North”); move(“East”); // move(“Northeast”); // Error: Argument of type ””Northeast”” is not assignable to parameter of type ”Direction”. The output of the above code is as follows – Moving in the direction: North Moving in the direction: East Numeric Literal Types Numeric literal types are similar to string literals but allow you to specify exact numeric values as allowed types. Example In the code below, the ”SmallPrimes” type contains the small prime numbers till 11 as a value. The type of the ”prime” variable is ”SmallPrimes”. So, it can contain any value from 2, 3, 5, 7, or 11 only. type SmallPrimes = 2 | 3 | 5 | 7 | 11; let prime: SmallPrimes; prime = 7; console.log(prime); // 7 // prime = 4; // Error: Type ”4” is not assignable to type ”SmallPrimes”. On compiling, it will generate the following JavaScript code. let prime; prime = 7; console.log(prime); // 7 // prime = 4; // Error: Type ”4” is not assignable to type ”SmallPrimes”. The output of the above code is follows – 7 Combined Literal Types You can combine different types of literals (string, numeric, boolean) using union types to allow a variable to hold a set of specified values. Example In the code below, the ”MixedLiterals” type contains the “click”, 404, and true values. The action variable can contain any singl value from the 3 values of the ”MixedLiterals” type. // Mixed type literals type MixedLiterals = “Click” | 404 | true; let action: MixedLiterals; action = “Click”; // Valid console.log(action); action = 404; // Valid console.log(action); action = true; // Valid console.log(action); // action = “Other”; // Error: Type ””Other”” is not assignable to type ”MixedLiterals”. On compiling, it will generate the following JavaScript code. let action; action = “Click”; // Valid console.log(action); action = 404; // Valid console.log(action); action = true; // Valid console.log(action); // action = “Other”; // Error: Type ””Other”” is not assignable to type ”MixedLiterals”. The output of the above code is as follows – Click 404 true Use Cases for Literal Types There are multiple use cases of literal types. However, we will look into some real-time use cases of the literal types. Configuration − It is used to define the particular configuration of variables or function parameters that take only specific values. State Management − Type literals can be used for state management. API Response Handling − It is used to handle the API response based on the API response status. Literal types in TypeScript enhance the type safety of your applications by allowing you to specify exactly what values are acceptable. It also helps developers maintain the code complexity and improve the readability. Print Page Previous Next Advertisements ”;
TypeScript – Strings
TypeScript – Strings ”; Previous Next In TypeScript, a string represents a sequence of characters. The string type is a fundamental data type in TypeScript. Strings are important to hold data that can be represented in text form. Like JavaScript, TypeScript also supports both string primitives and String objects. The String object lets you work with a series of characters. It wraps the string primitive data type with a number of helper methods. You can invoke methods on primitive strings because TypeScript automatically wraps the string primitive and call the methods on wrapper object. The same applies to properties also. Creating Strings Strings in TypeScript can be created as primitives from string literals or as objects using the String() constructor. You can use the following syntax to create a String object in TypeScript − cost str = new String(value); Here str is the newly created String object and value is a series of characters. You can create string primitives using single quote, double quotes and backtick. let str1: string = ”a string primitive”; let str2: string = “another string”; let str3: string = `yet another string`; The string primitives can also be created using the String() function without new keyword. let str: string = String(value); ”string” is a primitive, but ”String” is a wrapper object. Prefer using ”string” when possible. String Properties A list of the methods available in String object along with their description is given below − S.No. Property & Description 1. Constructor Returns a reference to the String function that created the object. 2. Length Returns the length of the string. 3. Prototype The prototype property allows you to add properties and methods to an object. String Methods A list of the methods available in String object along with their description is given below − S.No. Method & Description 1. charAt() Returns the character at the specified index. 2. charCodeAt() Returns a number indicating the Unicode value of the character at the given index. 3. concat() Combines the text of two strings and returns a new string. 4. indexOf() Returns the index within the calling String object of the first occurrence of the specified value, or -1 if not found. 5. lastIndexOf() Returns the index within the calling String object of the last occurrence of the specified value, or -1 if not found. 6. localeCompare() Returns a number indicating whether a reference string comes before or after or is the same as the given string in sort order. 7. match() Used to match a regular expression against a string. 8. replace() Used to find a match between a regular expression and a string, and to replace the matched substring with a new substring. 9. search() Executes the search for a match between a regular expression and a specified string. 10. slice() Extracts a section of a string and returns a new string. 11. split() Splits a String object into an array of strings by separating the string into substrings. 12. substr() Returns the characters in a string beginning at the specified location through the specified number of characters. 13. substring() Returns the characters in a string between two indexes into the string. 14. toLocaleLowerCase() The characters within a string are converted to lower case while respecting the current locale. 15. toLocaleUpperCase() The characters within a string are converted to upper case while respecting the current locale. 16. toLowerCase() Returns the calling string value converted to lower case. 17. toString() Returns a string representing the specified object. 18. toUpperCase() Returns the calling string value converted to uppercase. 19. valueOf() Returns the primitive value of the specified object. Examples Let’s understand the string types with the help of some examples in TypeScript. Example: Creating String Primitives In the example below, we use single quote, double quote and backtick to create the primitive strings str1, str2 and str3 respectively. let str1: string = ”a string primitive”; console.log(str1); let str2: string = “another string”; console.log(str2); let str3: string = `yet another string`; console.log(str3); On compiling, it will generate the following JavaScript code. let str1 = ”a string primitive”; console.log(str1); let str2 = “another string”; console.log(str2); let str3 = `yet another string`; console.log(str3); The output of the above example code is as follows − a string primitive another string yet another string Example: Creating String Objects Here we create a String object using the String() constructor with new keyword. const email = new String(”[email protected]”); console.log(email); console.log(typeof email); On compiling, it will generate the following JavaScript code. const email = new String(”[email protected]”); console.log(email); console.log(typeof email); The output of the above example code is as follows − [email protected] object Example: Concatenating TypeScript strings To concatenate two string, we can use + operator. Here, we concatenate two strings str1 and str2 and display the result in the console. let str1: string = “Hello “; let str2: string = “World!”; let str3: string = str1 + str2; console.log(str3); On compiling, it will generate the following JavaScript code. let str1 = “Hello “; let str2 = “World!”; let str3 = str1 + str2; console.log(str3); The output of the above example code is as follows – Hello World! Example: Accessing string elements using indexing In the example below, we access the string characters from the 1st and 6th indices. let message: string = “Hello World!”; console.log(“Character at index 1 is => ” + message[1]); console.log(“Character at index 6 is => ” + message[6]); On compiling, it will generate the following JavaScript code. let message = “Hello World!”; console.log(“Character at index 1 is => ” + message[1]); console.log(“Character at index 6 is => ” + message[6]); The output of the above example code is as follows − Character at index 1 is => e Character at index 6 is => W Example: String vs. string in TypeScript In TypeScript, type ”String” is a wrapper object and type ”string” is a primitive type. These both types can’t be assigned to each other. In the example below, we tried to assign a string object to a variable
TypeScript – Never
TypeScript – Never ”; Previous Next The never type The never type in TypeScript represents the values that can never occur. For example, the return type of a function that throws an error is never. function funcName(): never{ // it throws an exception or never returns } You cannot assign a value to a variable of never type – let x: never; x = 10; // throw error The above TypeScript code snippet will throw the following errors – Type ”number” is not assignable to type ”never”. You can use the never type as the return type of a function that never returns or always throws an exception. A function that never stops executing – function infiniteLoop(): never{ for(;;){} } Another example of function that never stops executing – function infiniteLoop(): never{ while (true) { } } Variables also acquire the type never when narrowed by any type guards that can never be true. The never type is used when we have exhausted all possible value and we don”t have anything to assign. function check(value: string | number) { if (typeof value === ”string”) { return “value is string”; } else { return “value is number”; } // here, not a string or number // “value” can”t occur here, so it”s type “never” } The never type is a subtype of, and assignable to, every type; however, no type is a subtype of, or assignable to, never (except never itself). Even any isn’t assignable to never. You can annotate a variable with never type, but it is very uncommon – function showError(): never{ throw new Error(“Error message from function with never as return type.”); } let x: never = showError(); In the above Typescript code snippet, variable x is annotated with the never type. The variable x is assigned showError() function that itself has the never as return type. void vs. never In TypeScript, a variable of void type can store undefined as a value. On the other hand, never can”t store any value. let val1: void = undefined; let val2: never = undefined; // error: Type ”undefined” is not assignable to type ”never”. We know that if a function in TypeScript does not return any value, it returns undefined. We generally annotate the type of return type of such function with void. Look at the below example, function greet(): void{ console.log(“Welcome to tutorials Point”); } let msg: void = greet(); console.log(msg); In the above example, we defined a function greet() that doesn”t return any value. When we call the function, the return value is undefined. On compiling, it will generate the following JavaScript code. function greet() { console.log(“Welcome to tutorials Point”); } let msg = greet(); console.log(msg); The output of the above code is as follows – Undefined Print Page Previous Next Advertisements ”;