Open In App

TypeScript Functions Type

Last Updated : 03 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

TypeScript function type is a type definition specifying the structure of a function, including its parameter types and return type. It ensures type safety when defining, passing, and using functions in TypeScript code.

Syntax:

function <functionName>(param1: type1, param2: type2): returnType {
//function body
return <value /expression >;
}

Parameters:

  • function: The keyword ‘function’ is used to create a function
  • functionName: Name of the function based on what the function does
  • param1,param2: Parameters listed in the function definition
  • type1,type2: Type of the parameters listed in the function
  • value/expression: The return value can be either value or expression
  • returnType: The return type of the function

There are several types of functions in TypeScript, which are listed below:

We will explore all the above-mentioned function types along with their basic implementation with the help of examples.

Named Function:

In TypeScript functions are defined and called by their name. It consists of type for parameters and return values.

Syntax:

function functionName( [args:type] ) :type{ } 

Example: here is the basic example of using named function in typescript.

Javascript




// Named Function Definition
function add(a: number, b: number): number {
    return a + b;
}
console.log(add(5, 2));


Output:

7

Anonymous Function:

An anonymous function in TypeScript is a function without a specific name, often defined inline, useful for one-off or small tasks where a named function isn’t needed.Function call can be made by using the variable to which it is assigned.

Syntax:

const variableName= function( [args:type] ) :type{ }  

Example: Here is the basic example of anonymous function in typeScript.

Javascript




// Anonymous Function
const subtract = function (a: number, b: number): number {
    return a - b;
};
console.log(subtract(5, 2));


Output:

3

Arrow Functions:

Arrow functions in TypeScript are concise function expressions using the => syntax. They retain the parent scope’s this and are often used for short, simple functions.

Syntax:

const variableName= ( [args:type] ) :type=> expression { }  

Example: Here is the basic example of above-mentioned method.

Javascript




//Arrow function
const multiply = (a: number, b: number): number => a * b;
console.log(multiply(5, 2));


Output:

10

Optional and Default Parameters in Functions:

Optional parameters in TypeScript allow you to specify function parameters that may be omitted when calling the function. Default parameters provide default values if no argument is passed.

Syntax:

function functionName ( arg1:type,arg2?:type ) :type { }  

Example: In this example, greeting is an optional parameter, and if this parameter is not provided, it returns the default value as “Hello” along with the name passed.And lastName is the default parameter if the lastName is not passed the default lastNAme in the function definition will be printed

Javascript




// Optional and Default parameters in function
function greet(firstName: string, lastName = 
    "Smith", greeting?: string,): string {
    if (greeting) {
        return `${greeting}, ${firstName} ${lastName}`;
    }
    return `Hello, ${firstName} ${lastName}`;
}
  
console.log(greet("John", "Doe"));
console.log(greet("Joe", undefined, "Hi"));


Output:

Hello, John Doe
Hi, Joe Smith

Return Type:

The return type in TypeScript specifies the data type a function should return. When we expect a function to return a particular type of value like either a string or a number then we can mention return types for functions by specifying a specific data type in TypeScript.

Syntax:

function functionName(parameters: parameterTypes): returnType {
// Function body
return value; // Returns a value of 'returnType'
}

Example: Here is the basic example of Return type function in typescript.

Javascript




function add(a: number, b: number): number {
    //expects number a return type
    return a + b;
}
const result = add(5, 15);
console.log(result);
  
function hello(msg: String): string {
    //expects string a return type
    return `${msg},Geeks !`;
}
const message = hello("Hello");
console.log(message);


Output:

20
Hello, Geeks !

Void Return Type:

In TypeScript, the void return type indicates that a function doesn’t return any value. It’s often used for functions that perform actions without producing a result.

Syntax:

function functionName(parameters: parameterTypes): void {
// Function body
// No 'return' statement or 'return;' is used
}

Example: Here is the basic example of Void return type function in typescript.

Javascript




function greet(name: string): void {
    console.log(`Hello, ${name}!`);
}
  
greet("Rahul");


Output:

 Hello, Rahul!

Rest Parameters:

Rest parameters in TypeScript allow a function to accept a variable number of arguments of the same type, collecting them into an array for easy processing within the function.

Syntax:

function functionName(...args: type): type { }

Example: Here is the basic example of using rest parameter in typescript function.

Javascript




//Rest parameter is passed in the function
function sum(...numbers: number[]): number {
    return numbers.reduce((acc, num) => acc + num, 0);
}
  
console.log(sum(1, 2, 3, 4, 5));


Output:

15

Function Overloading:

Function overloading in TypeScript enables defining multiple function signatures for a single function, allowing it to accept different parameter types or counts while providing type safety.

Syntax:

function functionName(arg1: type, arg2: type): type { }
function functionName(arg1: type, arg2: type, arg3: type): type { }

Example: Here is the basic example of the above-explained method.

Javascript




//Function overloading
function greet(name: string): string;
function greet(
    firstName: string, lastName: string): string;
  
function greet(...args: any[]): string {
    if (args.length === 1) {
        return `Hello, ${args[0]}!`;
    } else if (args.length === 2) {
        return `Hello, ${args[0]} ${args[1]}!`;
    }
    return "Invalid input!";
}
  
console.log(greet("Anne"));
console.log(greet("John", "Doe"));


Output:

Hello, Anne!
Hello, John Doe!

Callback Function:

Callback function is a function that can be accessed inside another function .Callback function can be passed as an argument to another function and is executed when a specific event or task is completed. Callbacks are commonly used in asynchronous operations, such as handling the result of a network request or responding to user interactions.

Syntax:

type callBackType = (callBackFunctionName: type) => returnType;

Example: In this example, two number type(a,b) parameters and a callback function(result) is passed to perform Operation function.

Javascript




//Callback function
type CallbackFunction = (result: number) => void;
  
function performOperation(a: number, b: number,
    callback: CallbackFunction): void {
    const result = a + b;
    callback(result);
}
  
performOperation(3, 4, (result) => {
    console.log(`Result: ${result}`);
});


Output:

7

References:



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads