Lab 06: Strict Mode & Null Safety

Time: 30 minutes | Level: Practitioner | Docker: docker run -it --rm node:20-alpine sh

strictNullChecks, optional chaining (?.), nullish coalescing (??), non-null assertion (!), definite assignment (!), and strict tsconfig flags.


Step 1: Setup

docker run -it --rm node:20-alpine sh
npm install -g typescript ts-node
mkdir /lab06 && cd /lab06
cat > tsconfig.json << 'EOF'
{
  "compilerOptions": {
    "target": "ES2020",
    "module": "commonjs",
    "moduleResolution": "node",
    "strict": true,
    "esModuleInterop": true
  }
}
EOF

💡 "strict": true enables: strictNullChecks, strictFunctionTypes, strictBindCallApply, strictPropertyInitialization, noImplicitAny, noImplicitThis, alwaysStrict.


Step 2: strictNullChecks


Step 3: Optional Chaining (?.)


Step 4: Nullish Coalescing (??) and Optional Assignment


Step 5: Non-Null Assertion (!)

💡 Prefer explicit checks over !. Reserve ! for cases where null genuinely can't occur but TypeScript can't infer it.


Step 6: Definite Assignment Assertion (!:)


Step 7: Strict tsconfig Flags Explained


Step 8: Capstone — Null-Safe API Client

Run:

📸 Verified Output:


Summary

Feature
Syntax
Purpose

strictNullChecks

"strict": true

Prevents null/undefined errors

Optional chaining

a?.b?.c

Safe property access

Nullish coalescing

a ?? 'default'

Fallback on null/undefined only

Non-null assertion

value!

Tell TS you know it's not null

Definite assignment

field!: Type

Promise to assign before use

Nullish assignment

a ??= value

Assign only if null/undefined

Last updated