Skip to main content

Archive

Show more

Function Signatures Understanding in TypeScript

Function Signatures Understanding in TypeScript

Function signatures in TypeScript allow you to define the structure and types of function parameters and return values. Understanding how to define and use function signatures is crucial for writing type-safe and maintainable code.


Basic Function Signatures

A function signature defines the types of parameters and the return type of a function. Here’s an example of a basic function signature:


let multiply: (x: number, y: number) => number;

multiply = (a, b) => {
  return a * b;
};

console.log(multiply(5, 3)); // Output: 15

Optional Parameters in Function Signatures

You can specify optional parameters in function signatures using the ? symbol. Optional parameters must come after required parameters:


let greet: (name: string, greeting?: string) => string;

greet = (name, greeting = "Hello") => {
  return `${greeting}, ${name}!`;
};

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

Rest Parameters in Function Signatures

Rest parameters allow a function to accept an indefinite number of arguments as an array. Here’s how to define a function signature with rest parameters:


let sum: (...numbers: number[]) => number;

sum = (...nums) => {
  return nums.reduce((total, num) => total + num, 0);
};

console.log(sum(1, 2, 3, 4)); // Output: 10

Function Signatures with Callbacks

Function signatures can include callbacks, which are functions passed as arguments to other functions. This is particularly useful for asynchronous operations:


let fetchData: (callback: (data: string) => void) => void;

fetchData = (cb) => {
  setTimeout(() => {
    cb("Fetched data");
  }, 1000);
};

fetchData((data) => {
  console.log(data); // Output after 1 second: Fetched data
});

Function Signatures with Overloads

Function overloads allow you to define multiple signatures for a single function. This is useful when a function can be called with different sets of parameters:


function getInfo(x: string): string;
function getInfo(x: number): number;
function getInfo(x: any): any {
  if (typeof x === "string") {
    return `Name: ${x}`;
  } else {
    return `Age: ${x}`;
  }
}

console.log(getInfo("Alice")); // Output: Name: Alice
console.log(getInfo(30));      // Output: Age: 30

Conclusion

Understanding function signatures in TypeScript is essential for writing robust and type-safe code. By defining the types of parameters and return values, you can catch errors early and ensure that your functions are used correctly. Whether you’re working with basic function signatures, optional parameters, rest parameters, callbacks, or overloads, TypeScript provides the tools you need to create clear and maintainable function definitions.

Comments