Skip to the solution
MediumFrontend11 min read

What is the difference between void, undefined and never as return types?

809 views

The problem

Question presented to candidate: "When you write a function's return type, what is the difference between void, undefined and never? When would you pick each one, and why can a callback typed () => void return a number?"

What a strong answer should cover:

  • void means "the caller should not use the result"; undefined means "the caller gets exactly the value undefined"; never means "this function never returns normally" (it always throws or loops forever)
  • Assignability: never is assignable to everything, undefined is assignable to void, but void is not assignable to undefined, and nothing except never is assignable to never
  • The void function-type rule: a callback type (x) => void accepts a function that returns a value (that is why arr.forEach(x => list.push(x)) compiles), while a declaration annotated : void may not return a value
  • Inference: no return gives void; a function declaration that only throws is still void, but a function expression or arrow that only throws is never; TypeScript 5.1 lets a : undefined function omit the return
  • never in control flow: after calling an explicitly annotated never function, the code is unreachable, so variables are narrowed (the basis of fail() and exhaustiveness helpers)

Code / implementation expected: Yes β€” three small functions with each return type, plus a callback example showing the void substitutability rule.

  • void
  • never

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

11 min read Β· 11 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

TypeScriptvoid, undefined and never as return types
TypeScriptvoid callbacks, strict undefined callbacks and never in control flow

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 30 of 81 in TypeScript

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

Up nextMedium

How do you type async functions and Promises?

Continue