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 meaningful 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, and therefore does not need to return a result, 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 saludar 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 a value. 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 resultado is void, because the imprimirMensaje function does not return any value.
In general, the void type is not used to declare variables. Its main purpose is for functions. However, some expressions can have a void type, especially when using functions with side effects.
