Step 4 – Functions and their types in TypeScript

Functions in TypeScript: An Overview

Functions in TypeScript are versatile tools that can be assigned to variables, passed around as arguments, and returned from other functions, just like in Java. This flexibility makes them powerful for creating reusable and maintainable code.

Defining Functions

To define a function in TypeScript, use the function keyword, followed by the function name, parameters, and the function body. Here’s how you define a function to add two numbers:

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

In Java, this would look like:

int add(int a, int b) {
  return a + b;
}

Here, add takes two parameters of type number and returns a number. TypeScript checks these types to ensure you’re using the function correctly.

Function Types

In TypeScript, you can describe the type of a function using function types. This is similar to declaring a method signature in Java. For example:

type AddFunction = (a: number, b: number) => number;

This type alias AddFunction specifies a function that takes two numbers and returns a number. You can then use this type to declare a function variable:

const add: AddFunction = (a, b) => {
  return a + b;
};

In Java:

// Declare a functional interface
@FunctionalInterface
interface AddFunction {
  int apply(int a, int b);
}

// Implement the interface
AddFunction add = (a, b) -> a + b;

Here, TypeScript infers the parameter and return types from the AddFunction type, so you don’t need to specify them again in the function implementation.

Optional and Default Parameters

TypeScript allows functions to have optional and default parameters. Optional parameters are marked with ?, and default parameters have a default value. Here’s an example:

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

console.log(greet("Alice")); // prints "Hello, Alice!"
console.log(greet("Bob", "Hi")); // prints "Hi, Bob!"

In Java:

String greet(String name, String... greeting) {
  if (greeting.length > 0) {
    return greeting[0] + ", " + name + "!";
  } else {
    return "Hello, " + name + "!";
  }
}

System.out.println(greet("Alice")); // prints "Hello, Alice!"
System.out.println(greet("Bob", "Hi")); // prints "Hi, Bob!"

Rest Parameters

Rest parameters allow a function to accept a variable number of arguments, which are collected into an array. Here’s an example:

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

console.log(sum(1, 2, 3)); // prints 6
console.log(sum(4, 5, 6, 7)); // prints 22

In Java:

int sum(int... numbers) {
  int total = 0;
  for (int number : numbers) {
    total += number;
  }
  return total;
}

System.out.println(sum(1, 2, 3)); // prints 6
System.out.println(sum(4, 5, 6, 7)); // prints 22

Conclusion

Functions in TypeScript are flexible and powerful, allowing you to define their types, use optional and default parameters, and handle a variable number of arguments. By using function types, optional parameters, and rest parameters, you can write clear, reusable, and type-safe code, similar to how you manage functions in Java.

Leave a Reply

Your email address will not be published. Required fields are marked *