Lab 05: Async TypeScript

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

Typed Promises, async/await error typing, Promise.all tuples, async generators, AbortController, and typed EventEmitter.


Step 1: Setup

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

Step 2: Typed Promises


Step 3: Async/Await with Error Typing


Step 4: Promise.all with Typed Tuples


Step 5: Async Generators


Step 6: AbortController with Types


Step 7: Typed EventEmitter


Step 8: Capstone — Async Pipeline

Run:

📸 Verified Output:


Summary

Concept
Pattern
Notes

Typed Promise

Promise<User>

Generic type parameter

Catch error

catch(err: unknown)

Always unknown, check instanceof

Result type

{ ok: true; value: T } | { ok: false; error: E }

Safer than throwing

Promise.all tuple

const [a, b] = await Promise.all([...])

Tuple type inferred

Async generator

async function*(): AsyncGenerator<T>

Lazy async sequences

AbortController

controller.signal

Timeout/cancel

Typed emitter

on<K extends keyof Events>

Type-safe events

Last updated