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:
voidmeans "the caller should not use the result";undefinedmeans "the caller gets exactly the valueundefined";nevermeans "this function never returns normally" (it always throws or loops forever)- Assignability:
neveris assignable to everything,undefinedis assignable tovoid, butvoidis not assignable toundefined, and nothing exceptneveris assignable tonever - The
voidfunction-type rule: a callback type(x) => voidaccepts a function that returns a value (that is whyarr.forEach(x => list.push(x))compiles), while a declaration annotated: voidmay not return a value - Inference: no return gives
void; a function declaration that only throws is stillvoid, but a function expression or arrow that only throws isnever; TypeScript 5.1 lets a: undefinedfunction omit thereturn neverin control flow: after calling an explicitly annotatedneverfunction, the code is unreachable, so variables are narrowed (the basis offail()and exhaustiveness helpers)
Code / implementation expected: Yes β three small functions with each return type, plus a callback example showing the void substitutability rule.