Lessons · TypeScript · null is not every type's member
null is not a string
With strictNullChecks, a value typed string cannot hold null or undefined. Say string | null when it can, and the compiler makes you check before using it.
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
'Cannot read properties of null' is the most common JavaScript crash. Strict null checks turn every one of them into a compile error at the line that forgot.
How to think about it
Turn strictNullChecks on (strict: true) and keep it on. Admit the missing case in the type, then handle it with a check, ?. or ??.
Worked example
let title: string = "ada";Never null.
title = null;Error: null is not a string under strictNullChecks.
let maybe: string | null = Math.random() > 0.5 ? "ada" : null;Say it can be null, and the compiler will not let you forget.
console.log(maybe ? maybe.length : 0);3 or 0: the check is required before .length compiles.
Your turn
A finder that may not find.
function find(id: number): string undefined { return id === 1 ? "ada" : undefined; }Solve one with the compiler running
The trap
Turning strictNullChecks off makes null assignable to everything and moves every null crash back to runtime.