Register Login
📑

On this page — Quick navigation

👇 Click any topic to scroll directly

Function in TypeScript

Introduction

Functions are one of the most important concepts in TypeScript and JavaScript. A function is a reusable block of code designed to perform a specific task. Instead of writing the same code multiple times, developers can place the logic inside a function and call it whenever needed.

TypeScript extends JavaScript functions by adding type safety, optional parameters, default values, interfaces, and many advanced features. This makes applications more reliable and easier to maintain.

Functions improve:

  • Code reusability
  • Readability
  • Maintainability
  • Testing
  • Modularity

In modern web development, functions are used everywhere—from handling user input to calling APIs and processing data.

What is a Function?

A function is a block of code that executes only when it is called. Functions can take input values called parameters and can return a result.

Functions help developers divide large programs into smaller manageable parts.

Basic Syntax of function

function functionName() {
    // code block
}

Example

function greet() {
    console.log("Hello World");
}

greet();

Types of Functions in TypeScript

1. Named Function

A function declared with a specific name.

function showMessage(): void {
    console.log("Named Function");
}

Use Case

Used for reusable logic across applications.

In TypeScript, you can define a named function with typed parameters and a typed return value like this:

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

Breakdown

  • function add → named function
  • a: number, b: number → parameter types
  • : number after parentheses → return type

More Examples

String return

function greet(name: string): string {
return `Hello, ${name}`;
}

2. Named Function with Optional Parameter

A named function in TypeScript is a function that has a specific name and can accept parameters.
An optional parameter is a parameter that does not need to be passed when calling the function.

Optional parameters are marked using ?.

function functionName(requiredParam: type, optionalParam?: type): returnType {
  // function body
}

Example with Explanation

function greet(name: string, title?: string): string {
  if (title) {
    return `Hello ${title} ${name}`;
  }

  return `Hello ${name}`;
}

Explanation

Function Name

greet

This is the name of the function.

3. Named Function with Rest Parameter

A rest parameter allows a function to accept multiple values as an array.

It is written using ... (three dots).

Syntax

function functionName(...parameterName: type[]): returnType {
  // function body
}

Example Program

function addNumbers(...numbers: number[]): number {
  let total = 0;

  for (let num of numbers) {
    total += num;
  }

  return total;
}

Explanation

Function Name

addNumbers

This is the name of the function.


Rest Parameter

...numbers: number[]

Meaning

  • ... → Rest operator
  • numbers → Parameter name
  • number[] → Array of numbers

The function can accept any number of numeric arguments.

Example:

addNumbers(10, 20, 30);

Inside the function:

numbers = [10, 20, 30]

Return Type

: number

The function returns a number.


Loop Explanation

for (let num of numbers)

This loop goes through each number in the array.


Adding Values

total += num;

Adds each number to total.


Function Calls

Example 1

console.log(addNumbers(10, 20));

Calculation

10 + 20 = 30

Output

30

Example 2

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

Calculation

1 + 2 + 3 + 4 + 5 = 15

Output

15

Required Parameter

name: string
  • name is required.
  • It must be a string.

Example:

greet("Rahul");

Optional Parameter

title?: string
  • title is optional because of ?.
  • You may pass it or skip it.

Return Type

: string

The function returns a string.


Full Program with Output

function addNumbers(...numbers: number[]): number {
  let total = 0;

  for (let num of numbers) {
    total += num;
  }

  return total;
}

console.log(addNumbers(10, 20));
console.log(addNumbers(1, 2, 3, 4, 5));

Result

30
15

Important Rules

 Only One Rest Parameter Allowed

✅ Correct:

function test(...nums: number[]) {}

❌ Wrong:

function test(...a: number[], ...b: number[]) {}

 Rest Parameter Must Be Last

✅ Correct:

function test(name: string, ...marks: number[]) {}

❌ Wrong:

function test(...marks: number[], name: string) {}

Another Example

function showNames(...names: string[]): void {
  console.log(names);
}

showNames("Rahul", "Aman", "Priya");

Output

[ 'Rahul', 'Aman', 'Priya' ]

4. Anonymous Function

An anonymous function is a function without a name.

It is usually:

  • stored in a variable
  • passed as an argument
  • used for short operations

A function without a name assigned to a variable.

let greeting = function () {
    console.log("Anonymous Function");
};

greeting();

Use Case

Commonly used in callbacks and event handling.

Basic Example

let greet = function(name: string): string {
  return "Hello " + name;
};

console.log(greet("Rahul")); output
Hello Rahul Explanation

Variable Name

greet

The anonymous function is stored inside the variable greet.

Anonymous Function

function(name: string): string

Notice:

  • There is no function name
  • So it is called an anonymous function

5.Anonymous Function with Optional Parameter

let welcome = function(name: string, title?: string): string {
  if (title) {
    return `Welcome ${title} ${name}`;
  }

  return `Welcome ${name}`;
};

console.log(welcome("Rahul"));
console.log(welcome("Rahul", "Mr."));

Output

Welcome Rahul
Welcome Mr. Rahul

6.Anonymous Function with Rest Parameter

let sum = function(...numbers: number[]): number {
  let total = 0;

  for (let n of numbers) {
    total += n;
  }

  return total;
};

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

Output

10

7.Anonymous Function as Callback

Anonymous functions are commonly used as callback functions.

let numbers = [1, 2, 3];

numbers.forEach(function(num) {
  console.log(num);
});

Output

1
2
3

8. Arrow Function

An Arrow Function is a shorter way to write functions in TypeScript and JavaScript.

It uses the => symbol and is commonly used for:

  • short functions
  • callbacks
  • cleaner code

Arrow Function Syntax

let functionName = (parameters): returnType => {
  // function body
};

Arrow function Example

let greet = (name: string): string => {
  return "Hello " + name;
};

console.log(greet("Rahul"));

Real-World Example

Login Function

function login(username: string, password: string): boolean {
    if (username === "admin" && password === "1234") {
        return true;
    }

    return false;
}

console.log(login("admin", "1234"));

Explanation

Difference Between Named and Anonymous Function

Named Function Anonymous Function
Has a function name No function name
Can be called directly by name Usually stored in variable
Easier to reuse Mostly used for short tasks