The void
type is used to indicate that a function does not return any value, or a variable should not have any usable value.
Example 1: Function Returning void
function warnUser(): void {
console.log("This is my warning message");
}
- The
void
return type signifies that thewarnUser
function does not return anything (it just performs an action, like logging a message).
Example 2: Assigning void
to a Variable
let unusable: void = undefined;
unusable = null; // OK if `--strictNullChecks` is not enabled
- A variable with the
void
type can only be assignedundefined
ornull
. - If
--strictNullChecks
is not enabled,null
is also allowed as a valid value forvoid
.
Key Points:
void
is typically used as the return type of functions that don’t return a value.- Variables with the
void
type can holdundefined
ornull
, but only under certain compiler settings.