The void Type

The type for functions that don't return anything.

TypeScript3 min readConcept 4 of 54

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.

function log(msg: string): void {
console.log(msg);
}

const result = log("Hello");

// TS blocks this because result is 'void'
result.toUpperCase();
log() performs a side-effect, returning void
result 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.

  1. 1What is the primary use case for the 'void' type in TypeScript?

Remember this

  • void represents the absence of a returned value.
  • It prevents developers from accidentally using the result of a side-effect function.
  • Unlike undefined, void does not force you to write a return statement.

Done with this concept?

Mark it complete to track your progress. No login needed.