TYPESCRIPT
TypeScript Void: Syntax, Usage, and Examples
The void
type in TypeScript represents the absence of a return value in a function. You typically use it when a function performs an action, like logging to the console, rather than computing and returning a value. Unlike undefined
, which is a specific value, void
means no value should be returned.
How to Use Void in TypeScript
Defining a Void Function
When a function does not return anything, declare its return type as void
.
function logMessage(message: string): void {
console.log(message);
}
logMessage("Hello, TypeScript!"); // Output: Hello, TypeScript!
If you try to return a value from a void
function, TypeScript throws an error.
function incorrectFunction(): void {
return "This causes an error"; // Error: Type 'string' is not assignable to type 'void'.
}
Using Void in Function Expressions
You can define function expressions with void
to explicitly indicate that they don’t return a value.
const notifyUser: () => void = () => {
console.log("User notified!");
};
notifyUser(); // Output: User notified!
Void in Callbacks
When passing a function as a callback, you can specify void
to ensure it doesn’t return a value.
function executeCallback(callback: () => void): void {
callback();
}
executeCallback(() => console.log("Executing callback...")); // Output: Executing callback...
Void in Interfaces
In TypeScript, void
helps define methods in interfaces that perform actions without returning data.
interface Logger {
log(message: string): void;
}
const consoleLogger: Logger = {
log(message) {
console.log(message);
},
};
consoleLogger.log("Logging data..."); // Output: Logging data...
When to Use Void in TypeScript
Functions Performing Side Effects
Use void
when a function modifies the application state, logs data, or performs actions without returning a value.
function sendAlert(message: string): void {
alert(message);
}
sendAlert("This is a warning!");
Callbacks That Should Not Return Data
Specifying void
in a callback ensures that the function only executes an action and does not produce a result.
function handleEvent(callback: () => void): void {
callback();
}
handleEvent(() => console.log("Handling event..."));
Type Safety in Object-Oriented Code
When defining class methods that modify object properties but don’t return anything, void
provides clarity.
class Counter {
private count: number = 0;
increment(): void {
this.count++;
console.log(`Count is now ${this.count}`);
}
}
const counter = new Counter();
counter.increment(); // Output: Count is now 1
Examples of Void in TypeScript
Logging Errors Without Returning a Value
Functions that log errors but don’t return anything should use void
.
function logError(errorMessage: string): void {
console.error(`Error: ${errorMessage}`);
}
logError("Invalid input detected!"); // Output: Error: Invalid input detected!
Using Void in Asynchronous Functions
A function that performs an asynchronous operation but does not return data should use Promise<void>
.
async function fetchData(url: string): Promise<void> {
await fetch(url);
console.log("Data fetched successfully");
}
fetchData("https://api.example.com");
Event Handlers Using Void
Event handlers in TypeScript should have a void
return type since they don’t return meaningful data.
document.addEventListener("click", () => {
console.log("Page clicked!");
});
Learn More About Void in TypeScript
Void vs. Undefined
Although void
suggests a function does not return a value, JavaScript technically returns undefined
when no return
statement is present.
function returnVoid(): void {
console.log("This function returns nothing");
}
console.log(returnVoid()); // Output: This function returns nothing
// Output: undefined
This difference matters when working with strict type checking. While void
indicates a function should not return anything, undefined
is an actual value that can be assigned or checked.
Void vs. Never
void
means a function does not return a meaningful value but still completes execution.never
means a function never reaches its end, typically because it throws an error or runs indefinitely.
function throwError(message: string): never {
throw new Error(message);
}
function logMessage(message: string): void {
console.log(message);
}
Use never
for functions that should not return at all, while void
is for functions that finish execution but don’t return anything useful.
Promise
When working with asynchronous operations, returning Promise<void>
ensures that a function completes but does not produce a return value.
async function saveData(): Promise<void> {
await new Promise((resolve) => setTimeout(resolve, 1000));
console.log("Data saved successfully!");
}
saveData();
Using Void in Type Assertions
Sometimes, you may want to assert that a function does not return a value. Assigning the result of an unknown function to void
prevents unintended use of its return value.
const fetchData: () => any = () => "Some response";
const result: void = fetchData(); // Allowed, but prevents using the return value
The void
type in TypeScript is essential for functions that do not return a meaningful value. Whether you’re defining event handlers, working with callbacks, or structuring class methods, void
provides clarity and prevents unintended use of return values.
Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.