TypeScriptBasic types
void
The return type of functions that return nothing.
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
#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
voidespecially 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
#- void vs nevervoid means a function returns no useful value, while never means a function never returns at all: it throws an error or runs forever.
- Function typesTyping parameters, the return value, and functions themselves as values.
- neverThe type of a value that never occurs: functions that don’t end normally, and impossible cases.
- null and undefinedThe types for the absence of a value, controlled by strictNullChecks.
Spotted a mistake or missing an example? Write to us.