Skip to content

Null & Undefined

Null and undefined are primitive types (set tsconfig.json - “strictNullChecks”: true; disabled by default)

let value: string | undefined | null = null;
value = "Hello World!";
value = undefined;

Optional chaining with ?. allows us to access properties on an object that may be null or undefined

interface Warehouse {
  sqft: number;
  yard?: {
    sqft: number;
  };
}
function printYardSize(warehouse: Warehouse) {
  const yardSize = warehouse.yard?.sqft;
  if (yardSize === undefined) {
    console.log("No yard");
  } else {
    console.log(`Yard is ${yardSize} sqft`);
  }
}

let workspace: Warehouse = {
  sqft: 500,
};

printYardSize(workspace); // Prints 'No yard'

Writing expressions that have a fallback value when null or undefined is encountered

function printDistance(distance: number | null | undefined) {
  console.log(`Distance: ${distance ?? "Unavailable"}`);
}

printDistance(null); // Prints 'Distance: Unavailable'
printDistance(0); // Prints 'Distance: 0'

The ! tells TypeScript “trust me, this isn’t null/undefined”:

function getValue(): string | undefined {
  return "Hello World!";
}

let value = getValue();
console.log(value!.length); // 12 - we assert it's not undefined

Use sparingly - if you’re wrong, you’ll get a runtime error.

TypeScript assumes array access never returns null or undefined (unless undefined is part of the array type).

let array: number[] = [1, 2, 3];
let value3 = array[0]; // with `noUncheckedIndexedAccess` this
// has the type `number | undefined`