Which return type to use when there is nothing to return in a function in TypeScript?

January 4, 2022 - 1 min read

When there is nothing to return in a function, you can use the : symbol (colon) followed by the keyword void after the parameters brackets of a function in TypeScript.

TL;DR

// logs string to the console
// The void keyword is to denote
// that the function doesn't
// return anything
function log(str: string): void {
  console.log(str);
}

For example, let's say we want to create a function where we need to only log the string to the console. Here the function doesn't have a return statement.

It can be done like this,

// logs string to the console
function log(str: string) {
  console.log(str);
}

Since the function doesn't have a return statement we can use the void keyword after the parameters brackets to denote that the function doesn't return anything.

It can be done like this,

// logs string to the console
// The void keyword is to denote
// that the function doesn't
// return anything
function log(str: string): void {
  console.log(str);
}

See the above code live in codesandbox.

That's all 😃!

Feel free to share if you found this useful 😃.