Skip to main content

Archive

Show more

Defining Function Types in TypeScript

Defining Function Types in TypeScript

TypeScript allows you to define the types of functions to ensure that they accept and return values of the specified types. This enhances type safety and code readability.


Basic Function Type

You can define the type of a function by specifying the types of its parameters and its return type. Here’s an example:


let add: (a: number, b: number) => number;

add = (x, y) => {
  return x + y;
};

console.log(add(5, 3)); // Output: 8

Optional Parameters

You can define optional parameters in a function type by using the ? symbol:


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

Rest parameters allow you to pass an arbitrary number of arguments to a function. Here’s how to define a function type 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 Types with Callbacks

TypeScript supports defining function types that include callbacks. This is useful for asynchronous functions:


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
});

Conclusion

Defining function types in TypeScript is a powerful feature that ensures your functions are used correctly throughout your codebase. By specifying parameter types, optional parameters, rest parameters, and callback functions, you can write more robust and maintainable code. Leveraging these function types can significantly enhance the readability and reliability of your TypeScript applications.

Comments