void and never

void: No Useful Return Value

void is the return type of a function that does not return anything (it actually returns undefined).

Example

function logOrder(id: string, amount: number): void {
  console.log(`[ORDER] ${id} Rs. ${amount}`);
}

const result = logOrder("OD-77", 1250);
console.log(result);

Output

[ORDER] OD-77 Rs. 1250
undefined

never: This Cannot Happen

never is the type of values that never exist. A function returns never when it always throws or loops forever. It is also what is left after you have handled every case of a union.

Example

Inside the default branch every status has been handled, so status is never. If someone adds a new status later and forgets a case, this line becomes a compile error.

function fail(message: string): never {
  throw new Error(message);
}

type Status = "PLACED" | "SHIPPED" | "DELIVERED";

function label(status: Status): string {
  switch (status) {
    case "PLACED": return "Order placed";
    case "SHIPPED": return "On the way";
    case "DELIVERED": return "Delivered";
    default: {
      const unreachable: never = status;
      return fail("Unknown status " + unreachable);
    }
  }
}

console.log(label("SHIPPED"));
console.log(label("DELIVERED"));

Output

On the way
Delivered

Summary

TypeMeaningTypical use
anyanything, no checksavoid; quick migration from JS
unknownanything, must check before useJSON, API data, catch errors
voidno return valuefunctions like loggers, event handlers
neverno value can existfunctions that always throw, exhaustive checks