The void
type in TypeScript represents the absence of a value. It is similar to the concept of void
found in other programming languages (like C++ and C#).
It is primarily used in the context of functions to indicate that a function does not return any significant value.
When a function is designed to perform an action (sometimes called a side effect), such as modifying a state or printing a message to the console, it does not need to return a result, and the void
type is specified.
function greet(): void {
console.log("Hello, world!");
}
let result: void = greet(); // Correct, but unnecessary
// result = 1; // Error: Cannot assign type 'number' to type 'void'.
In the previous example, the greet
function has a return type of void
, meaning it does not return any value.
void
is a subtype of undefined
. This means that the value undefined
is a valid representation of the void
type and can be used in contexts where a void
value is expected.
Variable Assignment
A variable of type void
cannot be assigned. It can only receive undefined
as a value.
function printMessage(message: string): void {
console.log(message);
}
const result: void = printMessage("Message without return value");
console.log(result); // undefined
Here, the type of the variable result is void
, as the printMessage
function does not return any value.
In general, the void
type is not used to declare variables. Its primary purpose is in functions. However, some expressions can have a void
type, especially when using functions with side effects.
Common Use Cases
Side Effect Functions
Functions that are used to perform actions but do not need to return a value, such as functions that print to the console or modify global variables, usually have a return type of void
.
function logMessage(message: string): void {
console.log(message);
}
logMessage("This is a log message."); // This is a log message.
Interfaces
In interfaces, methods that do not return a value are also defined with the void
type.
interface Processor {
start(): void;
stop(): void;
}
class Computer implements Processor {
start(): void {
console.log("Computer started.");
}
stop(): void {
console.log("Computer stopped.");
}
}
let pc: Computer = new Computer();
pc.start(); // Computer started.
pc.stop(); // Computer stopped.