← Back to TypeScript Course | Chapter 2: Basic Types | Lesson 8 of 11

Void Type

The void type is commonly used for functions that do not return a useful value. A function with a void return type can perform an action without producing a result for the caller.

Basic Void Function

A function can explicitly declare void as its return type to signal that it performs an action but does not return a usable value. This is the TypeScript equivalent of a function that just does something and returns undefined implicitly.

Example: Basic Void Function

typescript
function logMessage(): void {
  console.log("This is a message");
}
logMessage();

Void with Parameters

Void functions can still accept parameters completely normally, since the void type only describes what comes back out, not what goes in. A function can take three typed parameters and still be declared to return void.

Example: Void with Parameters

typescript
function logSum(a: number, b: number, label: string): void {
  console.log(`${label}: ${a + b}`);
}
logSum(2, 3, "Sum");

Void and Return Values

A function declared as returning void is only meant to signal it doesn't produce a meaningful result, even though it technically returns undefined under the hood. A function whose signature promises a different, non-void return type must actually provide a value matching that type.

Example: Void and Return Values

typescript
function logMessage(): void {
  console.log("Just performing an action");
  // return "text"; // rejected: doesn't match void
}
logMessage();

Void in Callbacks

Void return types are especially common for callback functions that perform an action rather than compute a value, such as event handlers. Array methods like forEach accept callbacks typed to return void, since any return value from the callback is simply ignored.

Example: Void in Callbacks

typescript
let numbers: number[] = [1, 2, 3];
numbers.forEach((n: number): void => {
  console.log(n * 2);
});

Void and Function Types

A function type itself can describe a void return value, such as () => void, letting a variable hold any function that performs an action without producing output. This is exactly the shape most event listener and side-effect callbacks take.

Example: Void and Function Types

typescript
let onClick: () => void;
onClick = () => console.log("Button clicked");
onClick();
🔒

Chapter Quiz — Complete all 11 topics to unlock

0/11 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.