By Hemanta Sundaray on 2023-04-10
Have you ever heard of the terms void and never in TypeScript?
They might sound a bit confusing but don't worry, I’m here to help you understand the difference between the two.
In TypeScript, every function has a return type. This return type represents the type of the value that the function will return once it completes its execution.
The never type is a special type in TypeScript that represents the type of a value that will never occur. A function that is assigned the never type is one that either keeps running forever or that throws an error and never returns.
For example, the arrow function below never returns, and the type checker will infer (guess) its return type as never.
const logger = () => {
while (true) {
console.log(“The server is up and running”)
}
}
In TypeScript, the void type is used to represent the absence of a value. Specifically, it is used to declare a function that doesn't return a value. Here’s an example:
function logError(errorMessage: string): void {
console.error(errorMessage)
}
void | never | |
---|---|---|
Function completes its execution | Yes | No |
A function with a void return type does complete its execution. This is different from the never type, which is used for functions that do not complete their execution, such as functions with an infinite loop or functions that always throw an error.