TypeScript, void represents the return value of functions that don’t return a value.
Syntax:
function functionName(parameters: ParameterType): void {
// Function body
// No return statement or return type annotation is needed
}
Example 1: In this example, function greet is the name of the function which is a void function, the name is the parameter, and its type is a string, indicating that the function expects a string argument.
function greet(name: string): void {
console.log(`Hello, ${name}!`);
} greet( "GeeksforGeeks" )
|
Output:
Example 2: In this example, logEvenNumbers is a void function that takes one parameter ‘max’ which is expected to be a number. Inside the function, it iterates through numbers from 0 to max and logs each even number to the console. Since it’s a void function, it doesn’t return a value.
function logEvenNumbers(max: number): void {
for (let i = 0; i <= max; i++) {
if (i % 2 === 0) {
console.log(i);
}
}
} logEvenNumbers(10) |
Output: