TypeScript void Type

Note: If you're new to TypeScript, check our Getting Started with TypeScript tutorial first.


In TypeScript, the void type indicates that a function does not return a value.

Here's a simple example of the void type. You can read the rest of the tutorial to learn more.

Example

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

logMessage("Good Morning!");  

// Output: Good Morning!

Here, the logMessage() function is declared to return void.


Using void in Function

You can use void in the function declaration as:

function functionName(): void {
    
    // Body of function

}

TypeScript void vs. JavaScript void

You must explicitly declare the return type as void if the function doesn't return a value in TypeScript.

TypeScript ensures type safety and will give an error if you attempt to return anything:

// TypeScript Code
function logMessage(message: string): void {
    console.log(message);
    // TypeScript will throw an error if you try to return a value
}

However, you don't need to specify a return type in JavaScript. Functions that don't return a value implicitly return undefined.

// JavaScript Code
function logMessage(message) {
    console.log(message);
}

void With Arrow Function

The void type is also applicable to arrow functions, indicating that the function doesn't return any value. For example,

const logClick = (): void => {
    console.log("Button clicked!");
}

logClick();

Output

Button clicked!

It is particularly useful in callbacks and event handlers where you do not want to return a value accidentally.


When to Use void?

Use the void type in TypeScript when defining functions meant to perform without returning any value.

For example, if you want to display an alert message without returning any value, you can use the void type:

function showAlert(): void {
    alert("Programming Expert Found!");
}

showAlert();

Functions with a void return type typically involve side effects such as updating the UI, logging messages to the console, or triggering actions where no return value is needed or expected.


Also Read:

Did you find this article helpful?

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges