Learn TypeScript

Understanding and using the void type

Understanding and using the void type

In this lesson, we will learn what the void type is and when to use it.

An example

Let's explore the void type .

TypeScriptOpen exercise in CodeSandbox

The code in the editor contains a function that outputs a string to the console.

🤔

The function doesn't return anything, so what is the return type of the function?

So, we could have explicitly defined the return type as follows:

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

The void type represents a function's return type when it doesn't return any data.

The void type can't hold any data - it can only be undefined (or null if the strictNullChecks compiler option is off).

  • Put the following code into the code editor:
let whatCanIHold: void;
whatCanIHold = undefined;
whatCanIHold = "something";

This shows the TypeScript compiler not happy with a variable of type void set to a string value.

Summary

So, void is only really useful for function return types. It can be inferred, but we can explicitly define it on functions if we prefer.

Further information about the void type can be found in the TypeScript handbook.

In the next lesson, we will learn how to strongly-type arrays.

On this page

© 2020 Carl Rippon
Privacy Policy
This site uses cookies. Click here to find out more