Difference Between never and void in TypeScript

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.

Understanding never in TypeScript

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.

Note: If a function body doesn’t have a return statement, it still returns a value of type undefined.

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”)
    }
}

Understanding void in TypeScript

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)
}

Difference Between void and never

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.

Join the Newsletter