Table of contents
1.
Introduction  
2.
Advantages
3.
TypeScript Arrow function
3.1.
Arrow /lambda function with a parameters
3.2.
Arrow /lambda function without a parameters
4.
Function creation in typescript
4.1.
Named function
4.2.
Anonymous function
5.
Function Parameters in typescript
5.1.
Optional Parameter
5.2.
Default Parameter
5.3.
Rest Parameter
6.
Frequently Asked Questions
7.
Key Takeaways   
Last Updated: Mar 27, 2024

Functions In TypeScript

Author Aryan Raj
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction  

In TypeScript,  we have the concept of classes, namespaces, and modules, but functions still play a vital role in describing how things actually work.

Javascript is a functional programming language, whereas Typescript is an application-scaling typed programming language built on javascript.

Functions are the building blocks of any application. By using functions, the code is readable, maintainable, and reusable. It organises the program into logical blocks of code.
 

A function initialization tells the code compiler about a function's name, return type, and parameters.

function greetings() {
	console.log("Namaste");
}
 
// calling of function
greetings();

 

Advantages

  • Without writing the same code, again and again, we can call a function several times.
  • Functions make our block of code compact.
  • We can easily identify the bug and rectify it. 

 

TypeScript Arrow function

Arrow Function or the Fat Arrow Function are easy ways of writing an anonymous function expression. We call this a fat arrow ( =>). 

This function is also called a Lambda function.

By the use of fat arrow =>, we can drop the use of the function keyword. All the parameters are passed in the parenthesis ( ), and the function expression is embraced within the curly brackets { }.

( [parameter1, parameter2,…parameter n] )=> {
         //codestatement
}

 

Arrow /lambda function with a parameters

let sum = (x: number, y: number): number => {
	return x + y;
}

sum(1, 5); //returns 6

 

 Here, the sum is a lambda function, "a: number, b: number" is a parameter type, and  ": number" is the return type. 

 

Arrow /lambda function without a parameters

let Print = () => console.log("Hello CodingNinjas!");  
Print();

 

It has only one statement. So, no need for a return key and curly brackets { }.

Function creation in typescript

TypeScript Function can be of two types:

  • Named function
  • Anonymous function

 

Named function

A named function is one where you have to declare and call back a function by its given name.

Syntax:

functionName( [arguments] ) { }
You can also try this code with Online Javascript Compiler
Run Code

 

Example:

//function definition
	function display() {
    console.log("Hello CodingNinjas");
}

//function call
display(); 
You can also try this code with Online Javascript Compiler
Run Code

 

Output:

Hello CodingNinjas

 

Anonymous function

Functions that are not bound to any function name are called anonymous functions. We can call it by using the variable name, which contains function.

Syntax:

Var res = function( [arguments] ) { }

 

Example:

let greeting = function() {
    console.log("Hello CodingNinjas");
};

greeting(); 

 

Output:

Hello CodingNinjas

Function Parameters in typescript

Parameters are the arguments that are passed to a function. The compiler expects a function to receive the exact same number and type of arguments as defined in the function signature. If the function expects some parameters, the compiler checks whether the user has passed values for that parameters or not. 

It will show the compilation error if the compiler does not match the same parameter as in the function signature.

 

 

Function parameter can be divided into the following:

  • Optional Parameter
  • Default Parameter
  • Rest Parameter 

 

Optional Parameter

A parameter can be marked optional by appending a question mark (?) to its name.

Optional parameters should be at the end and must follow the required parameters.

The TypeScript compiler will show an error if we try to invoke a function without providing the exact types of parameters as declared in its function signature.


Syntax:

function function_name (para1[:type], para2[:type], para3[:type])

 

Example:

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(101, "Abhi");
disp_details(102, "Ravi", "ravi@123.com");


In this example, the third parameter, i.e., mail_id is an optional parameter.

 

Output:

ID:101
Name Abhi
ID: 102
Name  Ravi
Email Id ravi@123.com


Default Parameter

TypeScript provides the option to add default values to parameters. So, If the user fails to provide a value to an argument, TypeScript will initialize the parameter with the default value. 

Default parameters can be removed while calling a function if the value is not passed for the default parameter in a function call. The default parameter must follow the required parameters in the function signature. The characteristic of the default parameter is the same as an optional parameter. 

 

Syntax:

function function_name(para1[:type],para2[:type] =  default_value) {
	// statement
}

 

Example:

function showName(name: string, greeting: string = "Hello"): string {
 	return greeting + '' + name + '!';
}

console.log(showName('CodingNinjas'));
console.log(showName('CodingNinjas', 'Hi'));

 

Output:

"Hello CodingNinjas!"        //Returns
"Hi CodingNinjas!"           //Returns 

 

Rest Parameter

The number of values you can pass to a function is not restricted in the rest parameters. 

But the values passed must all be of the same type.

It is useful where we have an undetermined number of parameters, and only one is allowed in a function.

The TypeScript compiler will create an array of arguments with the help of the rest parameter so that all array methods can work with the rest parameter. 

 

Syntax:

function function_name(para1[:type], para2[:type], ...para[:type]) { }  
You can also try this code with Online Javascript Compiler
Run Code

 

Example:

function add(...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)
}

add(7, 1, 1)
add(5, 10, 15, 20, 25)

 

Output:

sum of numbers 6
sum of numbers 50

 

Frequently Asked Questions

Q1. What is an anonymous function in TypeScript?

Ans: Anonymous Functions in TypeScript are functions that are not bound to an identifier i.e.; anonymous functions do not have a function name. They are used as inline functions. These are generally called when the function is used only once and does not require a name.

 

Q2. What is the arrow function in ES6?

Ans: Arrow functions are introduced in ES6, to provide you with a more accurate way of writing the functions in JavaScript. Arrow functions are anonymous functions.

 

Q3. What does () => void mean TypeScript?

Ans: The void type denotes the absence of having any type at all. It is the opposite of any type. Generally, we use the void type as the return type of functions that do not return a value.

 

Q4. The output of the above program is? 

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

 

Ans: 110

 

Read Also - Difference between argument and parameter

Key Takeaways   

In this article, we have discussed Functions in TypeScript, their functional parameters such as optional, Default, and Rest. We have also gone deeper into TypeScript arrow functions.

If you are pursuing a new career in Web Development, we suggest you get your fundamentals crystal clear with our Full Stack Development course
Check out this problem - Subarray Sum Divisible By K

This course will help you!

Live masterclass