void
void is the return type of a function that does its work but gives back no useful value.
void is written after the parameters: function f(): void. It tells the type checker that the function returns nothing worth using. If you try to use the result as a value, like storing it in a string, tsc complains.
In the course, addExpense(...): void changes the totals object it receives. It performs an effect and returns nothing. So whoever reads it knows to look at what changes, not at what is returned.
The : void is TypeScript syntax. Node erases it when running. At runtime, a function with no return gives back undefined.
function log(msg: string): void {
console.log(msg);
}
Reach for it when: a function exists for its effect (printing, changing an object, saving) and not for a value it returns.
Examples
Common mistake
function save(name: string): void {
console.log(name);
}
const result: string = save("a");Why: A void function does not return a string. Assigning its result to a string is a type error.
How to write it: If you need a value, change the return type and give it back with return.
