Execute Program

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 return statement?

  • 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'.Pass Icon
  • The void type indicates no value at all. In many other static languages, there are no exceptions: void truly can never have a value. But in TypeScript, weirdly, we can create a variable of type void. It can only hold the value undefined.

  • >
    const aVoid: void = undefined;
    aVoid;
    Result:
    undefinedPass Icon
  • (When TypeScript's "strictNullChecks" mode is off, a variable of type void can also hold the value null. 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, because void isn't assignable to anything!

  • >
    const aVoid: void = undefined;
    const u: undefined = aVoid;
    Result:
    type error: Type 'void' is not assignable to type 'undefined'.Pass Icon
  • In practice, you'll probably never encounter a variable of type void. But you will encounter many void functions, because any function without a return is automatically inferred to be void.