What does the void type mean, and how is it different from undefined?
void marks a function whose return value is meant to be ignored. undefined is an actual value. A function typed to return void may still be assigned a function that returns something, but its result cannot be used.
Explain it simply
A peon who delivers a letter does not hand anything back. You do not ask what he returned. That is void: the caller promises not to care.
undefined is different: it is a real value you can store, compare and return. A function that must return exactly undefined has to say so with a return statement.
The odd part is callbacks. If a parameter is typed () => void, TypeScript accepts a callback that returns a number too, because the result will be thrown away. This is why forEach accepts an arrow function that happens to return something.
Example
function log(msg: string): void {
console.log(msg); // no return needed
}
type Callback = () => void;
const cb: Callback = () => 42; // allowed: result ignored
// const x: number = cb(); // Error: void is not assignable to number
function explicit(): undefined {
return undefined; // must return, even if just undefined
}
[1, 2, 3].forEach(n => n * 2); // callback returns number, forEach expects voidWhat to say in the interview
"void means the return value should not be used; undefined is a concrete value. A function declared as returning void can still be satisfied by one that returns something, which is why callbacks like forEach are flexible. If I need to return exactly undefined I annotate undefined and write the return."
Common mistakes
- Using void as a variable type, where it is nearly useless.