Author: saqibkhan

  • The Rest Parameter

    The Rest Parameter

    In TypeScript, a rest parameter allows a function to accept a variable number of arguments and store them as an array. This is useful when you want to define a function that can handle a variable number of arguments.

    The rest parameter allows you to collect remaining arguments into a single array. The name of the rest parameter becomes the variable that holds this array.

    Rest Parameter Syntax

    The rest parameter is written using ellipsis/ three dots (…) followed by a parameter name in the function declaration. We use the array type for the type annotation of the rest parameter.

    functionfuncName(...rest: type[]): returnType{// function body;}

    Where,

    • funcName − It’s the name of our function.
    • …rest − it stores the multiple arguments to the array named rest.
    • type[] − it specifies the type of the arguments

    A function can have any number of ordinary parameters along with the rest parameter.

    A rest parameter must be last in the parameter list.

    functionfuncName(...rest1: type[], param1: type){}//Error : A rest parameter must be last in a parameter list.

    There must be only a single rest parameter in the function definition.

    functionfuncName(...rest1: type[],...rest2:number[]){}//Error: A rest parameter must be last in a parameter list.

    Same as above function declaration, the function expression can also have a rest parameter.

    letgetSum=function(...rest: type[]){function body;}

    Examples

    Let’s understand the rest parameters with help of some examples in TypeScript.

    Example: Variable Length Parameter List

    Using the rest parameter, we can call the function with a varying number of arguments. The rest parameter can handle these varying number of arguments.

    In the example below, we have defined a function named sum with a rest parameter …nums. The arguments are stored as elements of array nums. Each time we call the function with different number of arguments, nums stores the arguments. And we can perform any operation of array on nums.

    functionsum(...nums:number[]){let totalSum =0;for(let num of nums){
    
        totalSum += num;}return totalSum;}console.log(sum(10,20,30,40));console.log(sum(10,20));console.log(sum());</code></pre>

    On compiling, it will generate the following JavaScript code.

    functionsum(...nums){let totalSum =0;for(let num of nums){
    
        totalSum += num;}return totalSum;}console.log(sum(10,20,30,40));console.log(sum(10,20));console.log(sum());</code></pre>

    The output of the above example code is as follows −

    100
    30
    0
    

    Example: Accessing argument length

    In this example, we define a function named getLen with rest parameter ...theArgs. We use the length property of array to get the length or number of arguments.

    functiongetLen(...theArgs:number[]){console.log(theArgs.length);}getLen();getLen(5);getLen(5,6,7);

    On compiling, it will generate the following JavaScript code.

    functiongetLen(...theArgs){console.log(theArgs.length);}getLen();getLen(5);getLen(5,6,7);

    The output of the above example code is as follows −

    0
    1
    3 
    

    Rest Parameter & Spread Operator

    We have discussed about the rest parameters. The spread operator denoted with three dots (...) same as the rest parameters but works differently.

    A rest parameter is used to collect the remaining parameters as an array. The spread operator spreads out the elements of an array into individual elements.

    A spread argument must either have a tuple type or be passed to a rest parameter.

    Example: Array as spread arguments

    In this example, we defined two arrays arr1 and arr2 with three elements each. We call push() method on arr1 passing ...arr2 as an argument. This works as spread argument as it spreads out/ unpacks the elements of the arr2 into the individual elements.

    const arr1:number[]=[10,20,30];const arr2:number[]=[40,50,60];
    arr1.push(...arr2);console.log(arr1);

    On compiling, it will generate the following JavaScript code.

    const arr1 =[10,20,30];const arr2 =[40,50,60];
    arr1.push(...arr2);console.log(arr1);

    The output of the above code is as follows −

    [10, 20, 30, 40, 50, 60]
    

    Example: Finding max/min number

    In the example below, we find the maximum number. We define a function named getMax with a parameter, ...args: number[]. We call Math.max() method passing argument, ...args. The three dots in the argument, ...args, works as spread operator. It spreads/ unpacks the elements of the array args.

    functiongetMax(...args:number[]){// here ...args as rest parameterreturn Math.max(...args);// here ... works as spread operator}console.log(getMax(10,20,30,40));console.log(getMax(10,20,30));

    On compiling, it will generate the following JavaScript code.

    functiongetMax(...args){return Math.max(...args);// here ... works as spread operator}console.log(getMax(10,20,30,40));console.log(getMax(10,20,30));

    The output of the above example code is as follows −

    40
    30
    

    Example: Passing rest argument

    The rest argument unpacks the argument into the individual elements.

    In this example, we define a function named multiply that takes three parameters of number types and return their product. The return type of the function is also number. We call the function passing a rest argument (...numbers).

    functionmultiply(a:number, b:number, c:number):number{return a * b * c;}let numbers:[number,number,number];
    numbers =[2,3,4];console.log(multiply(...numbers));

    On compiling, it will generate the following JavaScript code.

    functionmultiply(a, b, c){return a * b * c;}let numbers;
    numbers =[2,3,4];console.log(multiply(...numbers));

    The output of the above example code is as follows −

    24
    
  • The Function () Constructor

    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 =newFunction(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 =newFunction("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 =newFunction("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 =newFunction("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 doesnt need a return statement with the function’ name.

    const sayHello =newFunction("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.

  • Anonymous Functions

    Anonymous Functions

    In TypeScript, the anonymous functions are the functions defined without a specific name. These functions are dynamically created at runtime. We can store them in variables and call them using those variables.

    We can define an anonymous function as a function expression.

    We can define a function in TypeScript using function declaration and function expression.

    Function declaration defined a named function. While to define an anonymous function, using function expression.

    Functions expression can be named but when a function expression is defined without name it called anonymous function.

    Defining Anonymous Functions with function keyword

    You can see the general syntax to create a named function in TypeScript.

    functionfuncName(param1:string, param2:number):void{// code for the function}

    The funcName is the identifier in the above function. We can make the above function anonymous by removing the funcName identifier. We can define the anonymous function by using the function keyword only, and the parameter in the parentheses after that. Also, we can store the anonymous function in the variable.

    You can follow the syntax below to create an anonymous function in TypeScript.

    Syntax

    We have converted the funcName() function to an anonymous in the below syntax:

    varfuncName:(param1:string, param2:string)=>void=function(
       param1:string,
       param2:string):void{// code for anonymous function};

    Now, the funcName is not a function identifier, but it stores a function. We have defined the type of the funcName variable, which is the function with two parameters of type string and return-type void. After that, we used the assignment operator to assign the anonymous function to the funcName variable.

    Example

    In the example below, we have defined the funcName variable and stored the anonymous function in that. You can observe how we have invoked the anonymous function using the funcName variable. We have also passed the two arguments while invoking the anonymous function using the funcName variable.

    In this example, we have created an array of numbers. After that, we invoked the sort() method to sort the numbers array in the decreasing number. The sort() method takes the callback function which returns the number value to sort the array, and the callback function is the anonymous arrow function.

    varfuncName:(param1:string, param2:string)=>void=function(
       param1:string,
       param2:string):void{// code for the anonymous functionconsole.log("The value of the param1 is "+ param1);console.log("The value of the param2 is "+ param2);};funcName("TutorialsPoint","TypeScript");

    On compiling, it will generate the following JavaScript code

    varfuncName=function(param1, param2){// code for the anonymous functionconsole.log("The value of the param1 is "+ param1);console.log("The value of the param2 is "+ param2);};funcName("TutorialsPoint","TypeScript");

    The above code will produce the following output

    The value of the param1 is TutorialsPoint
    The value of the param2 is TypeScript
    

    Defining Anonymous Function Using Arrow Function

    The arrow function is another type of anonymous function. Using the arrow syntax, we can define the function without the function keyword and function identifier.

    You can follow the syntax below to define the anonymous function using the arrow syntax and learn why it is called an arrow syntax.

    Syntax

    var test: function_Type =(parameters): return_type =>{// anonymous function code}

    In the above syntax, the test is a normal variable of the function type. Here, function_type is a type of arrow function. After that, () => {} is the syntax of the arrow function. Also, we can add parameters for the arrow function into the parentheses and can write code for the arrow function in the curly braces.

    Example

    In the example below, we have defined the test variable which stores the anonymous arrow function. The arrow function returns the number value after multiplying the value passed as a parameter.

    We have invoked the arrow function using the test variable and stored its return value in the result variable.

    In this example, we have created an array of numbers. After that, we invoked the sort() method to sort the numbers array in the decreasing number. The sort() method takes the callback function which returns the number value to sort the array, and the callback function is the anonymous arrow function.

    vartest:(valeu1:number)=>number=(value1:number):number=>{return10* value1;};var result =test(12);console.log("The returned value from the test function is "+ result);

    On compiling, it will generate the following JavaScript code

    vartest=function(value1){return10* value1;};var result =test(12);console.log("The returned value from the test function is "+ result);

    The above code will produce the following output

    The returned value from the test function is 120
    

    Using the above syntaxes and examples, we have learned to work with anonymous functions. We will learn where anonymous functions are used while writing real-time code.

    Using Anonymous Function as a Callback Function

    While working with TypeScript, we often need to call a callback function when invoking any method or function. We can pass the callback function as a parameter of another function. We can use the anonymous arrow function to keep the syntax sort of the callback function.

    You can follow the syntax below to use the arrow function as a callback function.

    Syntax

    Array.sort(()=>{// code for the callback function})

    In the above syntax, we have used the arrow function as a callback function.

    Example

    In this example, we have created an array of numbers. After that, we invoked the sort() method to sort the numbers array in the decreasing number. The sort() method takes the callback function which returns the number value to sort the array, and the callback function is the anonymous arrow function.

    var numbers:Array<number>=[90,64,323,322,588,668,9,121,34,1,2];
    numbers.sort((value1:number, value2:number):number=>{return value1 < value2 ?1:-1;});console.log(numbers);

    On compiling, it will generate the following JavaScript code

    var numbers =[90,64,323,322,588,668,9,121,34,1,2];
    numbers.sort(function(value1, value2){return value1 < value2 ?1:-1});console.log(numbers);

    The above code will produce the following output

    [ 668, 588, 323, 322, 121, 90, 64, 34, 9, 2, 1 ]
    

    We can create the anonymous function using two ways, one is only using the function keyword, and another is using the arrow syntax. However, arrow syntax is the best as its syntax is very short.

  • Default Parameters

    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

    functionfunctionName(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.

    Lets understand the function default parameters with the help of some TypeScript example programs.

    Example: Simple Default Parameters

    let’s look at the following example,

    functiongreet(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.

    functiongreet(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.

    functionsum(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.

    functionsum(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

    functionsum(x:number=10, y:number):number{return x + y;}console.log(sum(20,30));// 50console.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.

    functiongetNum():number{return10;}functionmul(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.

    functiongreet(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.

    functiongreet(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.

    functiongreet(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.

    functiongreet(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.

    functiongreet(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.
    
  • Optional Parameters

    The optional parameters in TypeScript allow us to specify function parameters may or may not be provided when calling the function.

    When a function is called without argument value for optional parameter, the default value of optional parameter is set to undefined. So inside the function body, we need to handle the optional parameter.

    A parameter can be made optional by adding a question mark after the its name in function definition.

    Syntax

    The syntax to defined a function with optional parameters in TypeScript is as follows −

    functionfunctionName(para1:type1, para2?:type2): returnType{// function body}

    In the above syntax, the function functionName is defined with two parameters − para1 and para2. The first parameter para1 is a required parameter and second parameter para2 is optional parameter.

    You can define a function with more than one optional parameters but the optional parameters must be the last parameters.

    JavaScript supports the optional parameters by default because in JavaScript, you can call a function without passing any argument even if it specifies the parameters.

    Examples

    Lets understand the function optional parameters with the help of some programming examples in TypeScript.

    Example: Using Optional Function Parameters

    In the example below, the function sum accepts three parameters, x, y, and z. The first two parameters x, and y are required parameters and the third parameter z is optional parameter.

    We first check if the optional parameter is true or not. If it is passed, we return the sum of all parameters else we return the sum of only required parameters. Look at the example.

    functionsum(x:number, y:number, z?:number):number{if(z){return x + y + z;}else{return x + y;}}console.log(sum(2,3));console.log(sum(2,3,5));

    On compiling, the above TypeScript code will be converted to the following JavaScript code.

    functionsum(x, y, z){if(z){return x + y + z;}else{return x + y;}}console.log(sum(2,3));console.log(sum(2,3,5));

    The output of the above example code is as follows −

    5
    10
    

    Notice when we call the sum function with only two arguments (without optional parameter), the if condition becomes false. The default value of an optional parameter (missing argument) is undefined.

    Example: Type Guards for Option Parameters

    We can use a type guard to check if the parameter has a valid value before using it.

    In the below example, we use type guard typeof age === ‘number’ to check if age has a value before using it.

    functiongreet(name:string, age?:number):void{if(typeof age ==='number'){console.log(You are ${age} years old.);}}greet('Shahid',35);

    On compiling, it will produce the following JavaScript code.

    functiongreet(name, age){if(typeof age ==='number'){console.log(You are ${age} years old.);}}greet('Shahid',35);

    The output of the above example code is as follows −

    You are 35 years old.
    

    Example: Optional parameters should be last parameters

    The optional parameters must be placed after the required parameters in the parameter list.

    functionadd(x?:number, y:number=30){return x + y;}console.log(add(2,3));

    In the above example, the optional parameter is put before the required parameter. The TypeScript compiler will throw the following error −

    'x' is possibly 'undefined'.
    

    Example: Optional parameters can’t have default values

    An optional parameter cant be initialized with a default value. In the below example, we have initialized the parameter y optional with a default value, 30.

    functionadd(x:number, y?:number=30){return x + y;}console.log(add(2,3));

    The TypeScript compiler will show the following error −

    Parameter cannot have question mark and initializer.
    

    The error shows that we cant assign a parameter as both optional and default.

    How to deal with it? The default parameters are optional parameters also.

    Example: Default values for optional parameters

    A default parameter is automatically an optional parameter. The default values are used for missing arguments if the function is called with missing values.

    functiongreet(name:string, age:number=35):void{console.log(Hello, ${name}!);console.log(You are ${age} years old.);}greet('Shahid');

    In the above example, we define the function greet with two parameters − name and age. The second parameter, age is initialized with default value. The parameter age works here as optional parameter.

    On compiling, it will generate the following JavaScript code.

    functiongreet(name, age =35){console.log(Hello, ${name}!);console.log(You are ${age} years old.);}greet('Shahid');

    The output of the above example code is as follows −

    Hello, Shahid!
    You are 35 years old.
    
  • Function Types

    Function types in TypeScript allows us to define the types for the functions.

    Function type describes the shape of the function, including the parameters and return values.

    Function types consist of the following −

    • Type of function parameters
    • Return type of the function

    Typing a Function

    Typing a function refers to specifying types for the its parameters and return values. Similar to how we add types to variables, we can also add type annotations to function parameters and return values as we define for the variables.

    Let’s see how typing a function works with a simple function,

    functionadd(x:number, y:number):number{return x + y;}letaddNums=function(x:number, y:number):number{return x + y;}

    In the first example, we added types for the parameters x and y and the return type of the function. TypeScript can infer the return type using the types of the parameters. This means that optionally we can leave the return type out.

    In the second example, we assigned a function to the variable addNums. While we didn’t explicitly define a type of addNums, TypeScript can infer its type.

    Lets now check how TypeScript compiler infers the type of a variable assigned with a function.

    TypeScript infers the type of the variable

    In the below example, we have assigned a function to variable add −

    letadd=function(a:number, b:number):number{return a + b;}

    The TypeScript compiler infers the type of the add variable as −

    (a:number, b:number)=>number

    Look at the following screenshot, the typescript editor infers the type of the add variable.

    Function Types Inference

    Here, “(a: number, b: number) => number” is basically a function type expression.

    The function type expression is a convenient way to declare a variable that hold a function.

    TypeScript Function Type Expression

    The function types in TypeScript can be defined using function type expressions. Function type expression is syntactically similar to the arrow function.

    Syntax

    Within function type expression, we specify the types of parameters and the return type. The syntax is as follows −

    (para1: type1, para2: type2,...)=> returnType
    

    Where,

    • (para1: type1, para2: type2, …): This defines the functions parameters and their types. We can add multiple parameters separated by commas.
    • =>: The fat arrow separates the parameters list from the return type.
    • returnType: This is the type of the return value of function.

    Example to demonstrate the function type in TypeScript −

    (name:string)=>void

    This function type is described as a function with one parameter, named name, of string type, that has no return value (indicated by void).

    (a:number, b:number)=>number

    In the above function type, it takes two parameters named a and b of number types and return a value of type number.

    Example

    Let’s declare a variable named addFun of function type using function type expression −

    letaddFun:(x:number, y:number)=>number=function(x:number, y:number):number{return x + y
    }console.log(addFun(2,3));

    In the above example, we add a function to addFun that takes two number as parameters and returns their sum. The type annotation “(x: number, y: number) => number” clarifies this behavior.

    On compiling this TypeScript code, it will generate the following JavaScript code.

    letaddFun=function(x, y){return x + y;};console.log(addFun(2,3));

    The output of the above example code is as follows −

    5
    

    Example

    Let’s take another example −

    constgreet:(name:string)=>string=(name)=>{returnHello, ${name}!;};console.log(greet("Shahid"));

    In the below example, we define a constant greet of type (name: string) => string. This function takes a string as a parameter and returns a string.

    The above TypeScript code will compile to the following JavaScript code.

    constgreet=(name)=>{returnHello, ${name}!;};console.log(greet("Shahid"));

    The output of the above example code is as follows −

    Hello, Shahid!
    

    Declaring Function Type Variable

    In TypeScript, we can declare a variable with a specific function type using function type expression.

    Lets declare a variable of function type −

    letadd:(a:number, b:number)=>number

    This declares a variable add of function type. The function takes two numbers as argument and returns a number.

    Example

    In the Example below, we declare the variable greet of the function type using function expression. And then assign the variable with a function that takes a parameter of type string and returns a string.

    letgreet:(name:string)=>string;greet=(name)=>{returnHello, ${name}!;};console.log(greet('John'));

    On compiling, it will generate the following JavaScript code −

    let greet;greet=(name)=>{returnHello, ${name}!;};console.log(greet('John'));

    The output is as follows −

    Hello, John!
    

    Specifying Function Parameters as Functions

    We can specify a parameter of type function. In the below example, the parameter fn is specified as of a function type. It accepts a parameter of type string and it does not return any value.

    The function greet accepts a parameter named fn, of type function.

    functiongreet(fn:(s:string)=>void){fn("Welcome to Tutorials Point!")}functionprint(str:string){console.log(str);}greet(print);

    On compiling, it will generate the following JavaScript code.

    functiongreet(fn){fn("Welcome to Tutorials Point!");}functionprint(str){console.log(str);}greet(print);

    The output of the above example code is as follows −

    Welcome to Tutorials Point!
    

    Using Type Aliases to Function Types

    We can create a type alias to represent a specific function type and use it within out code −

    typefuncType=(s:string)=>void;functiongreet(fn: funcType){fn("Welcome to Tutorials Point!")}functionprint(str:string){console.log(str);}greet(print);

    Here we define a type alias functType for the function type “(s: string) => void”. Further we use funcType as type of parameter in the definition of function greet.

    On compiling, it will generate the following JavaScript code.

    functiongreet(fn){fn("Welcome to Tutorials Point!");}functionprint(str){console.log(str);}greet(print);

    The output of the above example is as follows −

    Welcome to Tutorials Point!
    
  • Functions

    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 programs 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.NoFuntions & Description
    1.Defining a FunctionA function definition specifies what and how a specific task would be done.
    2.Calling a FunctionA function must be called so as to execute it.
    3.Returning FunctionsFunctions may also return value along with control, back to the caller.
    4.Parameterized FunctionParameters are a mechanism to pass values to functions.

    Optional Parameters

    Optional parameters can be used when arguments need not be compulsorily passed for a functions 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

    functiondisp_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 parameters 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.10functiondisp_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 dont 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

    functionaddNumbers(...nums:number[]){var i;var sum:number=0;for(i =0;i<nums.length;i++){ 
    
      sum = sum + nums&#91;i];}console.log("sum of the numbers",sum)}addNumbers(1,2,3)addNumbers(10,10,10,10,10)</code></pre>
    • The function addNumbers() declaration, accepts a rest parameter nums. The rest parameters 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 −

    functionaddNumbers(){var nums =[];for(var _i =0; _i < arguments.length; _i++){
    
      nums&#91;_i -0]= arguments&#91;_i];}var i;var sum =0;for(i =0; i &lt; nums.length; i++){
      sum = sum + nums&#91;i];}console.log("sum of the numbers", sum);}addNumbers(1,2,3);addNumbers(10,10,10,10,10);</code></pre>

    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

    functioncalculate_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.10functioncalculate_discount(price, rate){if(rate ===void0){ 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

    varmsg=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

    varres=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.10varres=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, function expressions are parsed only when the script engine encounters it during execution.

    When the JavaScript parser sees a function in the main code flow, it assumes Function Declaration. When a function comes as a part of a statement, it is a Function Expression.

    The Function Constructor

    TypeScript also supports defining a function with the built-in JavaScript constructor called Function ().

    Syntax

    var res = new Function( [arguments] ) { ... }.
    

    Example

    var myFunction =newFunction("a","b","return a * b");var x =myFunction(4,3);console.log(x);

    The new Function() is a call to the constructor which in turn creates and returns a function reference.

    On compiling, it will generate the same code in JavaScript.

    The output of the above example code is as follows −

    12 
    

    Recursion and TypeScript Functions

    Recursion is a technique for iterating over an operation by having a function call to itself repeatedly until it arrives at a result. Recursion is best applied when you need to call the same function repeatedly with different parameters from within a loop.

    Example Recursion

    functionfactorial(number){if(number<=0){// termination casereturn1;}else{return(number*factorial(number-1));// function invokes itself}};console.log(factorial(6));// outputs 720 

    On compiling, it will generate the same code in JavaScript.

    Here is its output −

    720
    

    Example: Anonymous Recursive Function

    (function(){var x ="Hello!!";console.log(x)})()// the function invokes itself using a pair of parentheses ()

    On compiling, it will generate the same code in JavaScript.

    Its output is as follows −

    Hello!!
    

    Lambda Functions

    Lambda refers to anonymous functions in programming. Lambda functions are a concise mechanism to represent anonymous functions. These functions are also called as Arrow functions.

    Lambda Function - Anatomy

    There are 3 parts to a Lambda function −

    • Parameters − A function may optionally have parameters
    • The fat arrow notation/lambda notation (=>) − It is also called as the goes to operator
    • Statements − represent the functions instruction set

    Tip − By convention, the use of single letter parameter is encouraged for a compact and precise function declaration.

    Lambda Expression

    It is an anonymous function expression that points to a single line of code. Its syntax is as follows −

    ( [param1, parma2,param n] )=>statement;
    

    Example: Lambda Expression

    varfoo=(x:number)=>10+ x 
    console.log(foo(100))//outputs 110 

    The program declares a lambda expression function. The function returns the sum of 10 and the argument passed.

    On compiling, it will generate following JavaScript code.

    //Generated by typescript 1.8.10varfoo=function(x){return10+ x;};console.log(foo(100));//outputs 110

    Here is the output of the above code −

    110
    

    Lambda Statement

    Lambda statement is an anonymous function declaration that points to a block of code. This syntax is used when the function body spans multiple lines. Its syntax is as follows −

    ( [param1, parma2,param n] )=> {
     
       //code block
    }
    

    Example: Lambda statement

    varfoo=(x:number)=>{    
       x =10+ x 
       console.log(x)}foo(100)

    The functions reference is returned and stored in the variable foo.

    On compiling, it will generate following JavaScript code −

    //Generated by typescript 1.8.10varfoo=function(x){
       x =10+ x;console.log(x);};foo(100);

    The output of the above program is as follows −

    110
    

    Syntactic Variations

    Parameter type Inference

    It is not mandatory to specify the data type of a parameter. In such a case the data type of the parameter is any. Let us take a look at the following code snippet −

    varfunc=(x)=>{if(typeof x=="number"){console.log(x+" is numeric")}elseif(typeof x=="string"){console.log(x+" is a string")}}func(12)func("Tom")

    On compiling, it will generate the following JavaScript code −

    //Generated by typescript 1.8.10varfunc=function(x){if(typeof x =="number"){console.log(x +" is numeric");}elseif(typeof x =="string"){console.log(x +" is a string");}};func(12);func("Tom");

    Its output is as follows −

    12 is numeric 
    Tom is a string
    

    Optional parentheses for a single parameter

    vardisplay= x=>{console.log("The function got "+x)}display(12)

    On compiling, it will generate following JavaScript code −

    //Generated by typescript 1.8.10vardisplay=function(x){console.log("The function got "+ x);};display(12);

    Its output is as follows −

    The function got 12
    

    Optional braces for a single statement, Empty parentheses for no parameter

    The following example shows these two Syntactic variations.

    vardisp=()=>{console.log("Function invoked");}disp();

    On compiling, it will generate following JavaScript code −

    //Generated by typescript 1.8.10vardisp=function(){console.log("Function invoked");};disp();

    Its output is as follows −

    Function invoked
    

    Function Overloads

    Functions have the capability to operate differently on the basis of the input provided to them. In other words, a program can have multiple methods with the same name with different implementation. This mechanism is termed as Function Overloading. TypeScript provides support for function overloading.

    To overload a function in TypeScript, you need to follow the steps given below −

    Step 1 − Declare multiple functions with the same name but different function signature. Function signature includes the following.

    • The data type of the parameter
    function disp(string):void; 
    function disp(number):void;
    
    • The number of parameters
    function disp(n1:number):void; 
    function disp(x:number,y:number):void;
    
    • The sequence of parameters
    function disp(n1:number,s1:string):void; 
    function disp(s:string,n:number):void;
    

    Note − The function signature doesnt include the functions return type.

    Step 2 − The declaration must be followed by the function definition. The parameter types should be set to any if the parameter types differ during overload. Additionally, for case b explained above, you may consider marking one or more parameters as optional during the function definition.

    Step 3 − Finally, you must invoke the function to make it functional.

    Example

    Let us now take a look at the following example code −

    functiondisp(s1:string):void;functiondisp(n1:number,s1:string):void;functiondisp(x:any,y?:any):void{console.log(x);console.log(y);}disp("abc")disp(1,"xyz");
    • The first two lines depict the function overload declaration. The function has two overloads −
      • Function that accepts a single string parameter.
      • Function that accepts two values of type number and string respectively.
    • The third line defines the function. The data type of the parameters are set to any. Moreover, the second parameter is optional here.
    • The overloaded function is invoked by the last two statements.

    On compiling, it will generate following JavaScript code −

    //Generated by typescript 1.8.10functiondisp(x, y){console.log(x);console.log(y);}disp("abc");disp(1,"xyz");

    The above code will produce the following output −

    abc 
    1 
    xyz 
    
  • dowhile loop

    The dowhile loop is similar to the while loop except that the do…while loop doesnt 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 dowhile 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

    Do While

    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.

    Lets now try an example of do…while loop in TypeScript.

    Example: dowhile

    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
    
  • While Loop

    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 JavaScripts 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

    While Loop

    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++;}</code></pre>

    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.

    Lets 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 =0for(; 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 =0while(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.

  • For Loop

    The for loop

    The for loop executes the code block for a specified number of times. It can be used to iterate over a fixed set of values, such as an array.

    The TypeScript offers two additional loop variants: for…in and for…of. These variants are particularly useful for iterating through iterables like arrays, strings, and maps.

    The for…of loop is generally preferred for iterating over iterables. It directly accesses the elements within the iterables.

    The for…in loop iterates the enumerable properties of an object. While it can be used with arrays or strings, it is generally not recommended for these cases.

    Syntax

    The syntax of the for loop is as below −

    for(initial_count_value; termination-condition; step){//statements }

    The loop uses a count variable to keep track of the iterations. The loop initializes the iteration by setting the value of count to its initial value. It executes the code block, each time the value of count satisfies the termination_condtion. The step changes the value of count after every iteration.

    Flowchart

    For Loop

    Example: Simple for loop

    var num:number=5;var i:number;var factorial =1;for(i = num;i>=1;i--){
       factorial *= i;}console.log(factorial)

    The program calculates the factorial of the number 5 and displays the same. The for loop generates the sequence of numbers from 5 to 1, calculating the product of the numbers in every iteration.

    On compiling, it will generate following JavaScript code.

    var num =5;var i;var factorial =1;for(i = num; i >=1; i--){
    
    factorial *= i;}console.log(factorial);</code></pre>

    The code produces the following output −

    120
    

    Example: The for loop with break statement

    var i:number=0;for(i; i <5; i++){if(i ==4){break;}console.log(i);}

    Inside the if condition, it breaks and exit the for loop when the value of i equals to 4. So it prints from 0 to 3 only.

    On compiling, it will generate the following JavaScript code.

    var i =0;for(i; i <5; i++){if(i ==4){break;}console.log(i);}

    The output of the above example is as follows

    0
    1
    2
    3
    

    Example: The for loop with continue statement

    var i:number=0;for(i; i <5; i++){if(i %2==0){continue;}console.log(i);}

    In the example above, the if condition (i % 2 == 0) evaluates to true, the execution control goes to then next iteration. The statements following the if block are skipped. When condition is false, the statements following the if block get executed.

    On compiling it will generate the following JavaScript code.

    var i =0;for(i; i <5; i++){if(i %2==0){continue;}console.log(i);}

    The output is as follows

    1
    3
    

    The for...in loop

    Another variation of the for loop is the for... in loop. The for in loop can be used to iterate over a set of values as in the case of an array or a tuple. The syntax for the same is given below −

    The for...in loop is used to iterate through a list or collection of values. The data type of val here should be string or any.

    Syntax

    The syntax of the for..in loop is as given below −

    for(var val in list){//statements }

    Lets take a look at the following examples −

    Example: The for...in loop with strings

    var j:any;var n:any="abc";for(j in n){console.log(n[j])}

    On compiling, it will generate the following JavaScript code

    var j;var n ="abc";for(j in n){console.log(n[j]);}

    It will produce the following output

    a 
    b 
    c
    

    Example: The for...in loop with arrays

    const arr:number[]=[10,20,30];for(var idx in arr){console.log(arr[idx]);}

    On compiling it will generate the following JavaScript code.

    const arr =[10,20,30];for(var idx in arr){console.log(arr[idx]);}

    The output of the above example code is as follows

    10
    20
    30
    

    Example: The for...in loop with tuples

    const tp:[string,number]=['TypeScript',20]for(var j in tp){console.log(tp[j])}

    On compiling, it will generate the following JavaScript code.

    const tp =['TypeScript',20];for(var j in tp){console.log(tp[j]);}

    The output of the above example code is as follows

    TypeScript
    20
    

    The for...of loop

    The for...of loop in another variant of the for loop. The for...of loop can be used to iterate through the values of iterables. For example, we can use the for...of loop to iterate through the array and get values from every index.

    Syntax

    The syntax of the for...of loop in TypeScript is as follows

    for(var element of iterable){// statements}

    Where,

    • element − It is a current element of the iterable.
    • of − It is a ES6 operator in TypeScript.
    • iterable − It is an iterable like an array, string, etc.

    Example: The for...of loop with arrays

    const arr:string[]=["Tutorialspoint","JavaScript","TypeScript"];for(var element of arr){console.log(element);}

    On compiling, it will generate the following JavaScript code.

    const arr =["Tutorialspoint","JavaScript","TypeScript"];for(var element of arr){console.log(element);}

    The output of the above example code is follows

    Tutorialspoint
    JavaScript 
    TypeScript
    

    Example: The for...of loop with strings

    let str:string="Hello";for(var char of str){console.log(char);}

    On compiling, it will generate the following TypeScript code.

    let str ="Hello";for(var char of str){console.log(char);}

    The output of the above example code is as follows

    H
    e
    l
    l
    o