Lab 10: Type Guards & Assertions

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

User-defined type guards (is), assertion functions (asserts x is T), the satisfies operator, branded/nominal types, opaque types.


Step 1: Setup

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

Step 2: User-Defined Type Guards (is)


Step 3: Generic Type Guards


Step 4: Assertion Functions


Step 5: The satisfies Operator


Step 6: Branded / Nominal Types


Step 7: Opaque Types Pattern


Step 8: Capstone — Full Type Safety Demo

Run:

📸 Verified Output:


Summary

Feature
Syntax
Purpose

Type guard

x is T return type

Narrow type in calling scope

Assertion

asserts x is T

Throw or narrow

satisfies

value satisfies Type

Validate without widening

Branded type

T & { _brand: B }

Prevent type confusion

Unique symbol

unique symbol

True nominal typing

Opaque type

Module-private brand

Maximum type safety

Last updated