When to Use 'never' vs 'void' in Your TypeScript Functions

When to Use 'never' vs 'void' in Your TypeScript Functions

When working with TypeScript, developers may come across the terms "never" and "void" while defining function return types. Both types signify the absence of a return value, but subtle differences exist between them.

"Void" is a type that represents the absence of a value returned by a function. It means that the function will execute but not return any data. It is useful when we want to perform some side-effect, like logging a message or updating a database, without returning any data.

On the other hand, "never" is a type that represents a function that will never return. It means the function will throw an error or enter into an infinite loop. It is useful when we want to signal that a function will never complete normally.

Consider the following examples:

In the example above, logMessage is a function that logs a message to the console and returns nothing, so its return type is void. throwError is a function that throws an error, so its return type is never. Finally, infiniteLoop is a function that enters into an infinite loop and never returns, so its return type is also never.

In summary, "void" is used when a function performs a side-effect and does not return any data, while "never" is used when a function will never complete normally. Understanding the differences between these types is important to use them correctly in your TypeScript code.


Tired of reading? Watch this video to see how Wojtek makes things quick and easy (available in Polish only).

Wyświetl ten post na Instagramie

Post udostępniony przez Ragnarson (@ragnarsoncom)