DEV Community

Jeferson Eiji
Jeferson Eiji

Posted on • Originally published at dev.to

How to Define Functions with Specific Argument and Return Types in TypeScript

TypeScript allows you to define functions with explicit argument and return types. This ensures type safety and helps catch errors at compile time.

Defining Argument and Return Types

You can annotate each parameter with its type and the return type after the function's parentheses.

Syntax:

function functionName(param1: Type1, param2: Type2): ReturnType {
  // function body
}
Enter fullscreen mode Exit fullscreen mode

Example 1: Simple Addition

function add(a: number, b: number): number {
  return a + b;
}
Enter fullscreen mode Exit fullscreen mode
  • a and b are both required to be numbers.
  • The function returns a number.

Example 2: String Formatter

function greet(name: string): string {
  return `Hello, ${name}!`;
}
Enter fullscreen mode Exit fullscreen mode
  • The parameter name must be a string.
  • The function returns a string.

Using Arrow Functions

You can also define typed arguments and return types in arrow functions.

const multiply = (x: number, y: number): number => x * y;
Enter fullscreen mode Exit fullscreen mode

Benefits

  • Prevents passing or returning incorrect types
  • Improves code documentation and readability

Tip

If a function doesnโ€™t return anything, use void as the return type:

function logMessage(msg: string): void {
  console.log(msg);
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)