Programming Language
TypeScript
Functions

TypeScript Functions

Introduction

Functions in TypeScript are reusable blocks of code that perform specific tasks. Functions improve code organization, enable modularity, and reduce redundancy in programming. TypeScript enhances traditional JavaScript functions with type annotations, ensuring better type safety and code reliability.


Advantages of Using Functions in TypeScript

  • Type Safety: Type annotations help prevent runtime errors.
  • Code Reusability: Functions can be called multiple times, reducing code duplication.
  • Improved Readability: Functions make code cleaner and easier to understand.
  • Supports ES6 Features: TypeScript supports modern function syntax, such as arrow functions.
  • Rich Features: Includes optional parameters, default parameters, function overloading, and more.

TypeScript Arrow Function

Arrow functions, also known as lambda functions, are a concise way to write functions. They use the => syntax and have a simpler structure compared to traditional functions.

Syntax:

const functionName = (parameters) => {
  // Function body
};

Arrow Function with Parameters

const add = (a: number, b: number): number => {
  return a + b;
};
 
console.log(add(5, 10)); // Output: 15

Arrow Function Without Parameters

const greet = (): void => {
  console.log("Hello, World!");
};
 
greet(); // Output: Hello, World!

Function Creation in TypeScript

Named Function

Named functions have an explicit name and are defined using the function keyword.

function multiply(a: number, b: number): number {
  return a * b;
}
 
console.log(multiply(3, 4)); // Output: 12

Anonymous Function

Anonymous functions are defined without a name and are often assigned to a variable.

const divide = function(a: number, b: number): number {
  return a / b;
};
 
console.log(divide(10, 2)); // Output: 5

Function Parameters in TypeScript

Optional Parameter

Parameters can be marked as optional by using a ? after the parameter name.

function greetUser(name?: string): void {
  console.log(`Hello, ${name ? name : "Guest"}!`);
}
 
greetUser(); // Output: Hello, Guest!
greetUser("Alice"); // Output: Hello, Alice!

Default Parameter

Default parameters have a pre-defined value if no argument is passed.

function calculateArea(length: number, width: number = 10): number {
  return length * width;
}
 
console.log(calculateArea(5)); // Output: 50
console.log(calculateArea(5, 4)); // Output: 20

Rest Parameter

Rest parameters allow a function to accept an indefinite number of arguments as an array.

function sumAll(...numbers: number[]): number {
  return numbers.reduce((acc, num) => acc + num, 0);
}
 
console.log(sumAll(1, 2, 3, 4)); // Output: 10

Function Types

TypeScript allows you to define the input and output types of functions. Common function return types include void, number, string, object, array, and more.

Void Function

A function with no return value.

function logMessage(message: string): void {
  console.log(message);
}
 
logMessage("Hello, TypeScript!");

Number Return Type

A function returning a number.

function add(a: number, b: number): number {
  return a + b;
}
 
console.log(add(5, 10)); // Output: 15

String Return Type

A function returning a string.

function greet(name: string): string {
  return `Hello, ${name}!`;
}
 
console.log(greet("Alice")); // Output: Hello, Alice!

Object Return Type

A function returning an object.

function createUser(name: string, age: number): { name: string; age: number } {
  return { name, age };
}
 
console.log(createUser("Alice", 30)); // Output: { name: "Alice", age: 30 }

Array Return Type

A function returning an array.

function getNumbers(): number[] {
  return [1, 2, 3, 4, 5];
}
 
console.log(getNumbers()); // Output: [1, 2, 3, 4, 5]

Return Statement

The return statement specifies the value a function should return. TypeScript enforces that the returned value matches the function's return type.

function square(num: number): number {
  return num * num;
}
 
console.log(square(4)); // Output: 16

this Keyword

The this keyword refers to the current object. In arrow functions, this is lexically bound, meaning it takes the value of this from the surrounding code.

class Counter {
  count = 0;
 
  increment = () => {
    this.count++;
  };
}
 
const counter = new Counter();
counter.increment();
console.log(counter.count); // Output: 1

Function Overloading

Function overloading allows you to define multiple function signatures with different parameter types or counts.

function display(value: string): void;
function display(value: number): void;
function display(value: any): void {
  console.log(value);
}
 
display("Hello"); // Output: Hello
display(123); // Output: 123

Callback Function in TypeScript

A callback function is passed as an argument to another function and is executed after the completion of the parent function.

function processData(data: string, callback: (processedData: string) => void): void {
  const result = data.toUpperCase();
  callback(result);
}
 
processData("hello", (output) => {
  console.log(output); // Output: HELLO
});

Closure in TypeScript

A closure is a function that retains access to its outer scope, even after the outer function has executed.

function createCounter(): () => number {
  let count = 0;
  return () => {
    count++;
    return count;
  };
}
 
const counter = createCounter();
console.log(counter()); // Output: 1
console.log(counter()); // Output: 2

TypeScript functions, with their enhanced type system and rich features, enable developers to write more robust, readable, and maintainable code.