Lesson 6 +10 XP

Null, Undefined & Void

Null, Undefined & Void

Understanding how missing values and return types work in TypeScript is critical for writing robust code.

Types Overview

  • undefined: Uninitialized variable or missing property.
  • null: Intentional absence of any object value.
  • void: Return type of functions that do not return a value.

strictNullChecks Setting

When strictNullChecks is enabled in tsconfig.json (recommended):

let name: string = "Alice";
// name = null; // Error! Type 'null' is not assignable to type 'string'.

let optionalName: string | null = null; // Allowed with Union type!

Void vs Never

// Returns nothing -> void
function logMessage(msg: string): void {
  console.log(msg);
}

// Never finishes normally -> never
function fail(): never {
  throw new Error("Fatal failure");
}

TL;DR

  • void is used for functions with no return statement.
  • Enable strictNullChecks to force explicit handling of null and undefined.
  • Use union types (string | null) to model optional or nullable values.