TS null / undefined
TypeScript treats null and undefined as distinct types. With strictNullChecks on, you can't accidentally call methods on them — the compiler makes you handle the empty case.
The default — strictNullChecks: true
TS
let name: string = 'Ada'; // name = null; // ✗ error // name = undefined; // ✗ error let middle: string | null = null; let phone: string | undefined = undefined;
Optional chaining
TS
const len = user?.name?.length; // number | undefined const fn = obj?.method?.(); // call only if obj and method exist const x = arr?.[0]; // safe array access
Nullish coalescing
TS
const name = user.name ?? 'anonymous'; // fall back if null/undefined const port = process.env.PORT ?? '3000'; // Notice: ?? does NOT treat 0 or '' as nullish, unlike ||. const cap = config.cap ?? 100; // 0 stays 0 const cap2 = config.cap || 100; // 0 becomes 100 (bug magnet)
Non-null assertion (use sparingly)
TS
const input = document.querySelector('input')!; // assert "this is non-null"
// Equivalent to: as HTMLInputElement (without changing type)
// A safer alternative:
const input2 = document.querySelector('input');
if (!input2) throw new Error('input missing');
input2.focus(); // narrowed
null vs undefined — convention
| Use case | Picks |
|---|---|
| Optional function parameter | undefined |
| "Value was deliberately cleared" | null |
| Missing JSON field | Depends on the API |
| React props | Mostly undefined |
Tip: Many style guides pick one and stick with it. The TypeScript repo itself uses
undefined almost exclusively. Pick a convention, document it, move on.Example
Example
// strictNullChecks: a value can be null/undefined only if you say so. let name: string = 'Ada'; // never null let middle: string | null = null; // may be null let phone: string | undefined; // may be undefined console.log(name, middle, phone);Try it Yourself »
Exercise
Optional-chaining operator.
user?
name
A single period.
Discussion
Loading…