TypeScript theorytheory 0/50 · 0%
Types · easy

9. null, undefined & strictNullChecks

Making absence of a value explicit and checked.

With `strictNullChecks` enabled (part of `strict` mode), `null` and `undefined` are not automatically assignable to other types — you must explicitly include them in a union.

ts
function findWallet(id: string): string | undefined {
  const found = id === "1" ? "0xabc" : undefined;
  return found;
}

const w = findWallet("1");
console.log(w.toUpperCase()); // error: w may be undefined
if (w) {
  console.log(w.toUpperCase()); // OK, narrowed to string
}

The non-null assertion operator `!` tells the compiler "trust me, this isn't null/undefined" — use sparingly, since it bypasses the safety strict null checks provide. Optional chaining (`?.`) and nullish coalescing (`??`) are the idiomatic way to work with possibly-absent values.

Check your understanding

  1. 1. What does `strictNullChecks` change?

  2. 2. What does the `!` non-null assertion operator do?

  3. 3. What does `a ?? b` return if `a` is `0`?