ProgramGuru

The void Type

Learn The void Type

void commonly describes a function whose return value is not meant to be used.

In this lesson, you will study the rule, run a complete TypeScript example, explain its output, and test a small change.

What you’ll learn

  • Explain the main rule behind the void type.
  • Predict the result of the complete runnable TypeScript example.
  • Recognize one common mistake and correct it.

Understand the concept

A function returning void may perform side effects such as logging or updating an object. It does not mean that the function body cannot contain a return statement; return; is allowed. In ordinary JavaScript, a function that does not return a useful result produces undefined at runtime.

Run a complete TypeScript example

Save this code as main.ts or paste it into the TypeScript Playground. The example uses fixed values so it runs without prompting for input.

TypeScript code

function announce(name: string): void {
   console.log(`Hello, ${name}`);
 }
 announce("Mina");

Verified output

Hello, Mina

How to run locally: npx tsc --strict --target es2022 --module commonjs main.ts, then node main.js. When using a project configuration, run the matching project build instead.

Trace the execution

Calling announce prints a greeting. The declared return type says callers should not rely on a useful returned value.

Predict the output before you run the sample. Compare each line with the source expression that produced it, and distinguish the type checker’s work from what happens in JavaScript at runtime.

Common mistakes and how to avoid them

Do not confuse void with never: a void function can finish normally, while a never-returning function cannot complete normally.

Debugging habit: when a change is rejected, read the exact compiler diagnostic and inspect the operand types. When it compiles but behaves unexpectedly, follow the values through the JavaScript expressions.

Practice it yourself

Add a second announce call and try assigning its result to a variable, then examine the inferred type.

Challenge: write down your prediction first, run the changed source, and explain any difference. Return to the verified version before continuing.

Check your understanding

Which function is a good candidate for void?
Choose one answer. You can try again.

Answer and explanation

One that logs a message and finishes without a useful result.

void communicates that callers should not use a return value.

Review the key idea

The void Type: A function returning void may perform side effects such as logging or updating an object.

void communicates that callers should not use a return value.

Before continuing, be able to explain what is checked before execution and what actually changes at runtime in the example above.

Reaching the recap and completing the quizzes are separate milestones.

    Next lesson: The never Type →