What does the void type mean?
What the void type means in TypeScript
The void type in TypeScript means:
"no return value".
That is, the function does something (has a side effect), but does not return any result.
Main purpose
The void type is most often used in function signatures -
to indicate that the function does not return a value.
javascript
function logMessage(): void {
console.log("Message to console");
}Here logMessage() performs an action but returns nothing -> void.
How to declare a function with void
javascript
function greet(name: string): void {
console.log(`Hello, ${name}!`);
}When called:
javascript
const result = greet("Tim");
console.log(result); // undefinedEven though the function has type
void, when called it actually returnsundefined. But TypeScript forbids using that value - it considers the function to return nothing.
An example with callbacks
The void type is often used in event handlers and callbacks,
when the return value does not matter.
javascript
type Callback = () => void;
function onClick(callback: Callback) {
callback();
}
onClick(() => {
console.log("Button click");
});The difference between void and undefined
| Type | Description | When it is used |
|---|---|---|
undefined | a concrete value (not defined) | variables with no value |
void | no return result | functions with no return |
Example:
javascript
let a: undefined = undefined; // the value exists
function doNothing(): void {} // the function returns nothingImportant details
- You cannot assign a value to a variable of type
void:
javascript
let nothing: void;
nothing = undefined; // OK
nothing = null; // Only if strictNullChecks is turned off
nothing = 42; // Error- A
voidfunction can have side effects, for example logging, sending a request, changing state, and so on.
javascript
function sendMessage(): void {
console.log("Message sent");
}- TypeScript distinguishes
voidfromnever:
void-> the function completes but returns nothing;never-> the function does not complete at all (an error or an infinite loop).
javascript
function log(): void {
console.log("ok"); // completes
}
function crash(): never {
throw new Error("error!"); // does not complete
}Summary
| Property | Description |
|---|---|
| Type | Primitive utility |
| Value | undefined (implicitly) |
| Where it is used | Function return type |
| Behavior | Indicates the function returns nothing |
Difference from never | void - the function completes, never - it does not |
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.