Member-only story

Never vs Void in TypeScript: Understanding Key Differences

Sumit kumar Singh
3 min readApr 10, 2023

In TypeScript, both never and void are used to represent the absence of a value, but they have different meanings and uses.

void is a type that represents the absence of a value, typically used for functions that do not return a value. For example:

function printMessage(message: string): void {
console.log(message);
}

In this example, the printMessage() function takes a string argument and logs it to the console, but it does not return a value. The void type is used to indicate that the function does not return a value.

never, on the other hand, is a type that represents a value that never occurs. It is typically used in functions that throw errors or have infinite loops. For example:

function throwError(message: string): never {
throw new Error(message);
}

function infiniteLoop(): never {
while (true) {
// do something
}
}

In these examples, the functions do not return a value because they either throw an error or have an infinite loop. The never type is used to indicate that these functions do not return a value that can be used.

Another important difference between void and never is how they interact with other types. void can be used as the return type for functions that…

--

--

Sumit kumar Singh
Sumit kumar Singh

Written by Sumit kumar Singh

YouTube: https://shorturl.at/8zZ4B Topmate: https://topmate.io/sumit_kr_singh 📚 HTML, Angular, React, and JavaScript 🧑‍💻 Tips & tricks

Responses (1)