TypeScript Functions Type (original) (raw)

Last Updated : 22 Jan, 2025

TypeScript function types define the structure of a function, including its parameter types and return type, ensuring consistent and type-safe usage.

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

`

**Parameters:

There are several types of functions in TypeScript, which are listed below. We will explore these function types along with their basic implementations and examples.

1. Named Function

In TypeScript, functions are defined and called by their name. They include types for parameters and return values.

**Syntax

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

TypeScript `

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

console.log(add(3, 4));

`

**Output:

7

2. 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. The function call can be made using the variable to which it is assigned.

**Syntax

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

TypeScript `

const subtract = function(a: number, b: number): number { return a - b; }

console.log(subtract(5, 2));

`

**Output:

3

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;

TypeScript `

const multiply = (a: number, b: number): number => a * b;

console.log(multiply(2, 5));

`

**Output:

10

4. 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 { }

TypeScript ``

function greet(firstName: string, lastName: string = "Doe"): string { return Hello, <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>f</mi><mi>i</mi><mi>r</mi><mi>s</mi><mi>t</mi><mi>N</mi><mi>a</mi><mi>m</mi><mi>e</mi></mrow><annotation encoding="application/x-tex">{firstName} </annotation></semantics></math></span><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.8889em;vertical-align:-0.1944em;"></span><span class="mord"><span class="mord mathnormal" style="margin-right:0.10764em;">f</span><span class="mord mathnormal">i</span><span class="mord mathnormal">rs</span><span class="mord mathnormal" style="margin-right:0.10903em;">tN</span><span class="mord mathnormal">am</span><span class="mord mathnormal">e</span></span></span></span></span>{lastName}; }

console.log(greet("John")); console.log(greet("Joe", "Smith"));

``

**Output:

Hello, John Doe
Hi, Joe Smith

5. 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, we can specify return types for functions.

**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.

TypeScript `

function square(num: number): number { return num * num; }

console.log(square(4));

`

**Output:

16

6. 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
}

TypeScript `

function logMessage(message: string): void { console.log(message); }

logMessage("Hello, Rahul!");

`

**Output:

Hello, Rahul!

7. 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 { }

TypeScript `

function sum(...numbers: number[]): number { return numbers.reduce((acc, curr) => acc + curr, 0); }

console.log(sum(1, 2, 3, 4, 5));

`

**Output:

15

8. 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;
function functionName(...args: any[]): any {
// Implementation
}

TypeScript ``

function greet(person: string): string; function greet(person: string, age: number): string; function greet(person: string, age?: number): string { if (age !== undefined) { return Hello, <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mrow><mi>p</mi><mi>e</mi><mi>r</mi><mi>s</mi><mi>o</mi><mi>n</mi></mrow><mo separator="true">,</mo><mi>y</mi><mi>o</mi><mi>u</mi><mi>a</mi><mi>r</mi><mi>e</mi></mrow><annotation encoding="application/x-tex">{person}, you are </annotation></semantics></math></span><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.625em;vertical-align:-0.1944em;"></span><span class="mord"><span class="mord mathnormal">p</span><span class="mord mathnormal">erso</span><span class="mord mathnormal">n</span></span><span class="mpunct">,</span><span class="mspace" style="margin-right:0.1667em;"></span><span class="mord mathnormal">yo</span><span class="mord mathnormal">u</span><span class="mord mathnormal">a</span><span class="mord mathnormal">re</span></span></span></span>{age} years old!; } return Hello, ${person}!; }

console.log(greet("Anne")); console.log(greet("John", 30));

``

**Output:

Hello, Anne!
Hello, John, you are 30 years old!

9. Callback Function

A callback function is a function that 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.

TypeScript `

function performOperation(a: number, b: number, callback: (result: number) => void): void { let result = a + b; callback(result); }

performOperation(3, 4, (result) => { console.log(result); });

`

**Output:

7

Best Practices for Using TypeScript Function Types