TypeScript

11.Understanding Functions in TypeScript

Understanding Functions in TypeScript

Functions are fundamental building blocks in any programming language. In TypeScript, functions are reusable blocks of code that are written once and can be called multiple times throughout an application. The primary purpose of a function is to perform a specific task, and you can define functions with parameters, return types, and optional/default values.

In this blog post, we will explore different types of functions in TypeScript, including functions with parameters, optional parameters, rest parameters, default parameters, anonymous functions, recursion, lambda functions, and function overloads.


Basic Functions in TypeScript

Example 1: Simple Function

A basic function in TypeScript is defined with a function name, followed by parentheses () for parameters, and curly braces {} for the function body. Functions can have a return type or can simply perform operations like logging values.

Syntax:

function functionName() {
// Code to be executed
}

Example:

function employeeInfo() {
var f_name: string = 'Rajesh';
console.log('First Name: ' + f_name);
var l_name: string = 'Kumar';
console.log('Last Name: ' + l_name);
}

// Calling the function
employeeInfo(); // Output: First Name: Rajesh, Last Name: Kumar

In the example above, the function employeeInfo does not take any parameters but simply logs the first name and last name to the console.


Functions with Parameters

Functions in TypeScript can take parameters. These parameters are used to pass values to the function for it to process. You define parameters in the function signature, and when calling the function, you provide the corresponding arguments.

Example 2: Function with Parameters

function employeeInfo(fName: string, lName: string) {
var f_name: string = fName;
console.log('First Name: ' + f_name);
var l_name: string = lName;
console.log('Last Name: ' + l_name);
}

// Calling the function with arguments
employeeInfo('Rajesh', 'Kumar'); // Output: First Name: Rajesh, Last Name: Kumar

In this example, we define a function employeeInfo that takes two parameters: fName and lName. When calling the function, we pass the actual values for these parameters.


Optional Parameters

In some cases, you may want to make one or more parameters optional. In TypeScript, you can achieve this by appending a question mark (?) to the parameter name. If the parameter is not passed, it will be undefined.

Example 3: Function with Optional Parameter

function student_details(roll: number, fullname: string, email: string, mobile?: number) {
console.log("Roll Number: " + roll);
console.log("Full Name: " + fullname);
console.log("Email: " + email);
if (mobile !== undefined) {
console.log("Mobile: " + mobile);
}
}

student_details(123, 'Umar Rahman', 'saz3sumar@gmail.com');
student_details(111, 'Rajesh Kumar', 'rajesh@gmail.com', 8583959529);

Output:

Roll Number: 123
Full Name: Umar Rahman
Email: saz3sumar@gmail.com

Roll Number: 111
Full Name: Rajesh Kumar
Email: rajesh@gmail.com
Mobile: 8583959529

In this example:

  • The mobile parameter is optional.

  • If it’s not provided, the function simply skips displaying the mobile number.

  • The second function call provides a mobile number, so it is printed as well.


Rest Parameters

A rest parameter allows you to pass an arbitrary number of arguments to a function. The rest parameter is represented by three dots (...) followed by a variable name. The passed arguments are stored as an array.

Example 4: Function with Rest Parameters

function YearList(...years: number[]) {
for (let i = 0; i < years.length; i++) {
console.log(years[i]);
}
}

YearList(2017, 2018); // Output: 2017, 2018
YearList(2015, 2016, 2017, 2018, 2019); // Output: 2015, 2016, 2017, 2018, 2019

Explanation:

  • The YearList function can accept any number of arguments because we are using the rest parameter ...years.

  • The arguments passed are stored in the years array, and we use a for loop to print each year.


Default Parameters

In TypeScript, you can also specify default values for parameters. If no value is provided for a parameter during the function call, the default value will be used.

Example 5: Function with Default Parameters

function employeeList(salary: number, department: string, company: string = 'Suhanasoftech Pvt. Ltd') {
console.log('Company Name: ' + company);
console.log('Salary: ' + salary);
console.log('Department: ' + department);
}

employeeList(20000, 'Sales'); // Output: Company Name: Suhanasoftech Pvt. Ltd, Salary: 20000, Department: Sales
employeeList(30000, 'Technical', 'Acesoftech Academy'); // Output: Company Name: Acesoftech Academy, Salary: 30000, Department: Technical

Explanation:

  • The company parameter has a default value of 'Suhanasoftech Pvt. Ltd'.

  • If no company name is passed, it uses the default value. If a company name is passed, the default is overridden.


Anonymous Functions

An anonymous function is a function that is declared without a name. You typically assign it to a variable or use it as a callback. These functions are often used for short-lived operations.

Example 6: Anonymous Function

var TypeScript = function() {
return "I am learning TypeScript";
};

console.log(TypeScript()); // Output: I am learning TypeScript

Explanation:

  • The anonymous function is assigned to the TypeScript variable.

  • The function is invoked immediately when TypeScript() is called.


Recursive Functions

A recursive function is a function that calls itself. It is often used for problems that can be broken down into smaller subproblems, such as calculating factorials or traversing tree-like structures.

Example 7: Recursive Function (Factorial)

function factorial(number: number): number {
if (number <= 0) {
return 1; // Termination condition
} else {
return number * factorial(number - 1); // Recursive call
}
}

console.log(factorial(5)); // Output: 120

Explanation:

  • The factorial function calls itself until the base case (number <= 0) is reached.

  • This is an example of tail recursion, where the recursive call is the last operation.


Lambda Functions (Arrow Functions)

Lambda functions, also known as arrow functions, provide a concise way to define functions. They are often used for short functions and can be more readable in some scenarios.

Example 8: Lambda Function

var msg = (x: number) => 10 + x;
console.log(msg(45)); // Output: 55

Explanation:

  • The lambda function is defined with the => syntax.

  • The body of the function returns the result of 10 + x.


Function Overloads

TypeScript supports function overloading, where you can define multiple versions of a function with the same name but different parameter types or numbers of parameters.

Example 9: Function Overloading

function course(cname: string): void;
function course(fees: number, cname: string): void;

function course(a: any, b?: any): void {
console.log(a);
console.log(b);
}

course("JAVA"); // Output: JAVA, undefined
course(20000, "Angular JS"); // Output: 20000, Angular JS

Explanation:

  • The course function is overloaded to accept either a single string (cname) or a number (fees) followed by a string (cname).

  • The implementation handles both cases by checking the number of arguments passed.


Conclusion

Functions in TypeScript are essential for creating modular, reusable, and maintainable code. With various types of functions, such as those with parameters, optional parameters, rest parameters, anonymous functions, recursion, and lambda functions, TypeScript provides a wide range of flexibility for developers to choose the best way to structure their code.

In this blog post, we covered the following function types:

  • Basic Functions: Functions with no parameters.

  • Functions with Parameters: Functions that accept input parameters.

  • Optional Parameters: Parameters that are not required and have default values.

  • Rest Parameters: Functions that can accept a variable number of arguments.

  • Default Parameters: Parameters with a predefined default value.

  • Anonymous Functions: Functions without a name, used as values.

  • Recursive Functions: Functions that call themselves to solve problems.

  • Lambda (Arrow) Functions: Concise function definitions.

  • Function Overloads: Defining multiple versions of a function.

Leave a Reply

Your email address will not be published. Required fields are marked *