void and never
Special return types for functions that return nothing or never finish.
Syntax
function log(msg: string): void { }Two special types describe unusual returns:
void— the function returns nothing useful. Common for functions that only produce side effects like logging.never— the function never returns at all, for example because it always throws an error or loops forever.
Example
Loading editor…
Press Run to execute the code.
When to use it
- An event handler function annotated as void signals to callers that its return value should not be used.
- A function that always throws an error is typed as never, letting TypeScript know control never reaches the caller.
- An exhaustive switch helper typed as never catches unhandled union members at compile time.
More examples
void return type
Annotates a function that performs a side effect and returns nothing, communicating intent to callers.
function logMessage(msg: string): void {
console.log(`[LOG] ${msg}`);
// no return statement needed
}
const result = logMessage('hello'); // result is void — don't use itnever for always-throwing function
Types a helper that always throws as never, allowing TypeScript to treat it as an unreachable exit point.
function fail(message: string): never {
throw new Error(message);
}
function getUser(id: number): string {
if (id <= 0) fail('Invalid id'); // TypeScript knows this throws
return `user-${id}`;
}Exhaustive check with never
Uses never in the default branch so adding a new union member without a case triggers a compile-time error.
type Shape = 'circle' | 'square';
function describeShape(s: Shape): string {
switch (s) {
case 'circle': return 'round';
case 'square': return 'four sides';
default:
const _check: never = s; // Error if a new Shape is added without a case
return _check;
}
}
Discussion