Declaration & Arrow Functions

Explicit return types make functions easier to read and maintain:

// Function Declaration with explicit return type
function add(a: number, b: number): number {
  return a + b;
}

// Arrow Function with type inference
const multiply = (x: number, y: number): number => x * y;

// Usage examples
console.log(add(5, 3));      // 8
console.log(multiply(5, 3)); // 15

Callback Example

Using proper type annotations ensures you don’t misuse parameters:

function getUserName(callback: (data: string) => void): void {
  // Imagine this function fetches a username asynchronously
  const fakeUser = "Merrick";
  callback(fakeUser);
}

getUserName((data) => {
  console.log("Username:", data);
});

// The following callback would cause a compile error:
// getUserName((data) => {
//   console.log(data * 2); // Error: Cannot multiply a string
// });