TypeScriptBasic types

void

The return type of functions that return nothing.

On this page

Example

#
TypeScript
function logProgress(done: number, total: number): void {
  const percent = Math.round((done / total) * 100)
  console.log(`Progress: ${percent}%`)
}

const result = logProgress(3, 8)
console.log(result)
Result
Progress: 38%
undefined

Definition and usage

#

The void type means there’s no useful return value. A function that just does something (logs, saves, changes state) without returning a result has the return type void.

In practice, a function like that returns undefined, but void communicates intent: “don’t use the result.” The compiler reports an error if you try to return an actual value from it.

In the type of a callback function, void is looser: (item: string) => void lets you pass in a function that actually returns something. The result is simply ignored, which is why, for example, arr.forEach(x => list.push(x)) is valid.

Syntax

#
Syntax
function name(): void {
  …
}

More examples

#
A callback type with void
TypeScript
const saved: string[] = []
const onSave: (value: string) => void = (value) => saved.push(value)

onSave('Module 1')
console.log(saved)
Result
['Module 1']

Good practices

#
  • Add the return type void especially to public functions and event handlers. The code then says directly that the result doesn’t matter.
  • An async function with no result has the type Promise<void>.

Related entries

#

Spotted a mistake or missing an example? Write to us.