TypeScript ยท Chapter 11 of 44

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`.

Syntax
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.

Example 1 (typescript)
function logMessage(msg: string): void {
  console.log(msg);
}
logMessage("Saved!");
Output
Saved!

The function performs a side effect (logging) and returns nothing, so its return type is void.

Example 2 (typescript)
function fail(message: string): never {
  throw new Error(message);
}
try {
  fail("Something broke");
} catch (e) {
  console.log((e as Error).message);
}
Output
Something broke

fail 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.
๐Ÿ’ก Note: You will use `void` often for callbacks and event handlers, but `never` is rarer and mostly appears in error-throwing helpers.

๐Ÿ“ Quick Quiz

1. What does a `void` return type mean?

2. Which return type fits a function that always throws an error?

3. Can a function typed `void` still technically return undefined?