
What is the difference between never and void in TypeScript?
2 May, 2024
0
0
0
Contributors
In TypeScript, both never
and void
represent situations where a function doesn't return anything, but they're used in different contexts.
void
: Think of void
as the absence of a specific type. When a function returns void
, it means it doesn't return any value at all. It's like saying, "This function does its job, but it doesn't give anything back." You often see void
used with functions that perform some action but don't produce a meaningful result.
void:
function greet(name: string): void {
console.log(`Hello, ${name}!`);
}
greet("Alice"); // Output: Hello, Alice!
Here, the greet
function logs a greeting message to the console but doesn't return any value.
never:
never
: On the other hand, never
represents a situation where a function never finishes executing. It's typically used for functions that throw errors, enter infinite loops, or have unreachable code paths. When a function returns never
, it's saying, "This function doesn't just not return anything; it can't return anything because it never completes its execution.”
function throwError(message: string): never {
throw new Error(message);
}
function infiniteLoop(): never {
while (true) {
// do something forever
}ype
}
In these examples, throwError
always throws an error, and infiniteLoop
enters an infinite loop, so neither of these functions ever finishes executing normally.
So, in summary:
void
: The function completes its job but doesn't return any value.never
: The function never completes its execution under normal circumstances, often because of errors, infinite loops, or unreachable code.
Understanding these differences can help you use them appropriately in your TypeScript code.