Everyday TypeScript: Void
Welcome to the Void lesson!
This lesson is shown as static text below. However, it's designed to be used interactively. Click the button below to start!
What's the return type of a function that doesn't contain a
returnstatement?In TypeScript, that function's return type is
void. We can see that by causing a type error, then looking at the error message.(When a code example contains a type error, you can answer with
type error.)>
function f() {}const n: number = f();Result:
type error: Type 'void' is not assignable to type 'number'.
The
voidtype indicates no value at all. In many other static languages, there are no exceptions:voidtruly can never have a value. But in TypeScript, weirdly, we can create a variable of typevoid. It can only hold the valueundefined.>
const aVoid: void = undefined;aVoid;Result:
undefined
(When TypeScript's "strictNullChecks" mode is off, a variable of type
voidcan also hold the valuenull. In this course, "strictNullChecks" mode is always on.)This doesn't mean that we can then assign our void to a variable of type
undefined. That would be a type error, becausevoidisn't assignable to anything!>
const aVoid: void = undefined;const u: undefined = aVoid;Result:
type error: Type 'void' is not assignable to type 'undefined'.
In practice, you'll probably never encounter a variable of type
void. But you will encounter manyvoidfunctions, because any function without areturnis automatically inferred to bevoid.