iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

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 casePicks
Optional function parameterundefined
"Value was deliberately cleared"null
Missing JSON fieldDepends on the API
React propsMostly 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

Test yourself

Q1. strictNullChecks makes null and undefined…
Q2. Optional chaining uses…
Q3. Nullish coalescing (??) treats which as fallback triggers?

Discussion

Loading…