void is a type in typescripts, used in functions which does not return value.

Here is a function declaration with void type

function logError(error): void{
  console.log('Error occurred while calling a API ', error)
  }

compiler throws an error if function returns an value

advantages of void type:

  • void is an optional return type in typescript and allows developers to understand that function to return empty value, It allows readability of code
  • Type safety: if function declared with void type, code throws an error if function assigned to an variable where it does not return any value. This used to catch early errors in a code at compile time.
  • It helps developers to make a code constistence by declaring void to callback functions
  • Cleanup functions: functions that handles clean up code, usually returns void

void type example

  • Normally, functions with logging messages are declared with this type.
function logError(error): void{
  console.log('Error occurred while calling a API ', error)
  }

  • Async functions Async functions are asynchornous functions, calls external API’s and returns values as promises.

    if function returns nothing, promise is used as a return type

async  function getUsers(id: number): promise<void> {
  const response = await fetch(`https://api.website.com/users/${id}`);
  const user = await response.json();
  console.log("returned user:", user);
  }
// function called
  await getUsers(1)

  • DOM event handlers event handlers are used to trigger a code when a event occurs.

Below function addEventListener does not returned any value, hence void is used.

  document.getElementById("submit")?.addEventListener("click", function(): void {
  console.log("Submit button clicked!");
});
  • call back functions functions are passed to other functions as arguments, and return value is passed as a return type.

uses void for call back function and also arguments expression contains it.

function executeCallback(simpleCallback: () => void): void {
  console.log("Before callback");
  callback();
  console.log("After callback");
}

// Usage
simpleCallback((): void => {
  console.log("callback function called");
});