Skip to main content

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); // undefined

Even though the function has type void, when called it actually returns undefined. 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

TypeDescriptionWhen it is used
undefineda concrete value (not defined)variables with no value
voidno return resultfunctions with no return

Example:

javascript
let a: undefined = undefined; // the value exists function doNothing(): void {} // the function returns nothing

Important details

  1. 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
  1. A void function can have side effects, for example logging, sending a request, changing state, and so on.
javascript
function sendMessage(): void { console.log("Message sent"); }
  1. TypeScript distinguishes void from never:
  • 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

PropertyDescription
TypePrimitive utility
Valueundefined (implicitly)
Where it is usedFunction return type
BehaviorIndicates the function returns nothing
Difference from nevervoid - the function completes, never - it does not

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.