Skip to main content

Void Data Type in TypeScript

Void Data Type in TypeScript

The void data type in TypeScript is used to represent the absence of a value. It is primarily used to indicate that a function does not return a value. Understanding how to use void can help you write clearer and more predictable functions.


Basic Usage

The void type is commonly used as the return type for functions that do not return any value. Here’s a basic example:


function logMessage(message: string): void {
  console.log(message);
}

logMessage("This is a message"); // Output: This is a message

Functions and Methods for Void

Although the void type itself does not have methods, it is useful to know how to work with functions that have a void return type. Below is a table of common use cases involving void functions:

Function/Method Description
Function returning void Defines a function that performs an action but does not return a value.
Callback functions Functions passed as arguments to other functions that do not return a value.
Event handlers Functions that handle events (e.g., clicks, key presses) which do not need to return a value.

Examples of Functions Returning Void

Function Returning Void

Here’s an example of a function that performs an action and does not return a value:


function greet(name: string): void {
  console.log(`Hello, ${name}!`);
}

greet("Alice"); // Output: Hello, Alice!

Callback Function

Here’s an example of a function that takes a callback function as a parameter. The callback function has a void return type:


function processInput(input: string, callback: (result: string) => void): void {
  const result = input.trim().toUpperCase();
  callback(result);
}

processInput("hello", (result) => {
  console.log(result); // Output: HELLO
});

Event Handler

Here’s an example of an event handler function with a void return type:


document.getElementById("myButton")?.addEventListener("click", () => {
  console.log("Button clicked!");
});

Conclusion

The void data type in TypeScript is essential for functions that do not need to return a value. It helps in defining functions that perform actions such as logging, event handling, or executing callbacks. By using void appropriately, you can create clear and concise functions in your TypeScript code.

Comments