乐闻世界logo
搜索文章和话题

What is the difference between never and void in typescript?

1个答案

1

In TypeScript, 'never' and 'void' are two highly specialized types that play crucial roles in defining return types for functions, yet they serve distinct purposes and convey different meanings.

Void

The void type is commonly used to denote that a function does not return any value. Once the function completes execution, it yields no result, and we typically specify its return type as void. This is primarily applicable in scenarios where the function focuses on performing actions or side effects (e.g., logging to the console, modifying global variables) without needing to return data.

Example:

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

In this example, the logMessage function outputs a message to the console and does not return any value, so void is appropriately used as the return type.

Never

The never type represents the return type of functions that can never complete normally (i.e., cannot reach a termination point). This includes functions that throw exceptions and those with infinite loops.

Example:

typescript
function throwError(errorMsg: string): never { throw new Error(errorMsg); } function infiniteLoop(): never { while (true) { } }

In both functions, throwError never completes normally because it consistently throws an error; infiniteLoop never completes due to its infinite loop structure. Using never as the return type indicates that the function has no valid normal return path.

Summary

In summary, void is used for functions that return no value, while never is used for functions that will never return (due to exceptions or infinite loops). Understanding this distinction helps accurately describe the behavior and expectations of functions.

2024年6月29日 12:07 回复

你的答案