TypeScript never and void
The `void` type represents the absence of a return value, and is commonly used as the return type of functions that don't return anything meaningful, like ones that only log a message.
The `never` type represents values that never occur โ for example, a function that always throws an error or loops forever never actually returns, so its return type is `never`.
function log(msg: string): void {
console.log(msg);
}
function fail(msg: string): never {
throw new Error(msg);
}void
Functions annotated with `: void` are expected to return `undefined` or nothing at all. It's the most common return type for functions used purely for their side effects.
never
`never` is used for functions that never successfully complete, such as ones that always throw, and also appears when TypeScript narrows a type down to nothing possible remaining.
function logMessage(msg: string): void {
console.log(msg);
}
logMessage("Saved!");Saved!The function performs a side effect (logging) and returns nothing, so its return type is void.
function fail(message: string): never {
throw new Error(message);
}
try {
fail("Something broke");
} catch (e) {
console.log((e as Error).message);
}Something brokefail never returns normally since it always throws, so its return type is never.
Key points
- `void` means a function does not return a meaningful value.
- `never` means a function never successfully returns.
- Functions that always throw errors are typed as returning never.
- void and never both differ from `undefined`, which is an actual value.
