The void Type
The type for functions that don't return anything.
The Absence of a Value
void is the opposite of any. It signifies the complete absence of a type.
You will almost exclusively see it used as the return type of functions that perform side effects (like updating the DOM or logging to the console) rather than returning a value.
Preventing Accidents
If you declare that a function returns void, TypeScript will stop you from accidentally assigning its result to a variable or attempting to chain methods off of it.
If you write const result = console.log('hello');, result is typed as void. If you then try to do result.toString(), the compiler blocks you.
Typing function returns
You specify void after the parameter list of a function:
typescript
function greet(name: string): void {
console.log(Hello, ${name}!);
// No return statement here
}
Try it
Watch how TypeScript handles a function typed with a void return. It enforces that you cannot use the resulting value.
log() performs a side-effect, returning voidresult becomes completely unusable. You cannot chain methods or access properties on it.Property 'toUpperCase' does not exist on type 'void'.
Check yourself
Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.
Remember this
voidrepresents the absence of a returned value.- It prevents developers from accidentally using the result of a side-effect function.
- Unlike
undefined,voiddoes not force you to write areturnstatement.
Done with this concept?
Mark it complete to track your progress. No login needed.