Void Type
In this page:
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
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
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
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
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
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: