Null and undefined
Concept and syntax
With strictNullChecks, null and undefined are distinct types, not automatically valid strings. A union string | null allows either text or null. Compare explicitly against null before using string operations. undefined often represents an omitted or uninitialized value; null can express explicit absence by convention. A check for absence should not discard a legitimate empty string or zero.
Working example
Compile standalone examples in a fresh directory with tsc --strict --target ES2022 --module commonjs --noEmitOnError main.ts, then node main.js.
function label(value: string | null): string { if (value === null) return "missing"; return value;}console.log(label(null), label("tea"));let absent: string | undefined = undefined;console.log(absent === undefined);Expected output (one line per log):
missing teatrueCommon mistake
Intentionally invalid; check this snippet separately. Do not run it.
Expected compiler diagnostic: TS2322. The annotation does not allow null under strictNullChecks. Widen it to string | null only when absence belongs in the contract.
Practice and recap
Call label with an empty string and null. Modify the function to accept undefined without discarding empty text.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Null and undefined — knowledge check
Check the concept, apply it to a new choice, and interpret a compiler diagnostic.
Which type allows both text and explicit null?
Why check value === null rather than only if (value)?
Which change models explicit absence while still permitting text?
let labelText: string = null;