void and never in TypeScript are different types:
Examples:
function log(message: string): void { console.log(message); } function throwError(message: string): never { throw new Error(message); } function infinite(): never { while (true) {} }
never is often used for exhaustiveness checking in switch-case statements by types:
type Shape = { kind: 'circle' } | { kind: 'square' }; function getArea(shape: Shape) { switch (shape.kind) { case 'circle': return 1; case 'square': return 2; default: const _exhaustive: never = shape; // The compiler will alert if a case is missed } } }
Can void and never be used interchangeably as function return types?
Answer: No. A function with a void type either returns undefined or returns nothing but completes execution. A function with a never type never successfully completes execution (it throws an error or goes into an infinite loop).
Example:
const fn: () => never = () => { // return; // Error: A function whose declared type is 'never' must not return. };
History
In an analytical system, a validation function was typed with a void return type, even though it always threw an exception. As a result, developers believed that the function could "return," and did not implement further checks, leading to missed error handling and incorrect implementation of the call chain.
History
In one of TypeScript projects, a function expected to have a strictly typed return type was defined to return never instead of void. This led to compilation errors and API compatibility issues when trying to call the function with a callback that was typed as never.
History
In a backend module, exceptions were previously thrown using a function with a void return type. After migrating to TypeScript, the compiler did not warn about code execution beyond the call to this function, resulting in unnecessary lines of "unreachable" code — only changing the return type to never helped identify such places and clean up the code, avoiding logical errors.