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!
TypeScript Functions Type
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:
Table of Content
- Named Function :
- Anonymous Function:
- Arrow Functions:
- Optional and Default Parameters in Functions:
- Return Type:
- Void Return Type:
- Rest Parameters:
- Function Overloading:
- Callback Function:
We will explore all the above-mentioned function types along with their basic implementation with the help of examples.