Hone

Lessons · TypeScript · strict null checks

Nothing has a type too

With strict null checks, null and undefined are their own types; a string cannot be null unless you say string | null.

Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.

What it is for

The billion-dollar mistake: crashes from values that were secretly null. Strict mode makes every possible null visible where it can occur.

How to think about it

Model absence in the type (T | null or an optional field), then handle it at the point of reading with ?., ??, or an early return.

Worked example

function city(u: { address?: { city?: string } } | null): string {
Absence is possible at three levels, and the type says so.
  return u?.address?.city ?? "n/a";
Every possible absence handled in one line.
}

Your turn

Provide the fallback.

const name = user?.name  "guest";

The trap

Using ! ('non-null assertion') to silence the error. It is a promise the compiler cannot check; if you are wrong, it crashes at runtime.

Practise strict null checks on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.