Context Typing Guide
Approaches for validation
Context Passing & Strong Typing Guide
Problem: Ensuring all required context is passed through the call chain without missing fields, type-safe.
Solution: Multi-layered validation using TypeScript and runtime checks.
Current Issue: Weak Context Typing
Problem Code
Risk: Silent Failures
Solution 1: Strict Interface Definition
Define Complete Context Types
Type-Safe Footer Formatting
Solution 2: Runtime Validation
Validate Context at Boundaries
Validate via Builder Pattern
Solution 3: Type-Safe Context Chain
Pipe Context Through Call Stack
Middleware Validates Context
Solution 4: Prevent Context Loss
Context Passing in Call Chain
Problem:
Solution:
Solution 5: Type Guards & Narrowing
Use TypeScript Type Guards
Implementation: Complete Example
Full Type-Safe Flow
Migration Plan
Phase 1: Add Type Definitions (Week 1)
- Define
TelegramContextFullinterface - Define
AdminTelegramContextinterface - Add type guards (
isAdminContext,hasMessagingFields)
Phase 2: Add Validation (Week 2)
- Add
assertAdminContext()assertions - Add
TelegramContextBuilderfor context creation - Validate at context creation points
Phase 3: Update Code (Week 3)
- Update
createTelegramContext()to use builder - Update footer logic to use type guards
- Update transport layer to validate context
Phase 4: Add Middleware (Week 4)
- Add context validation middleware
- Add context manager for tracking
- Add logging for context violations
Summary Table
| Approach | Pros | Cons | Use Case |
|---|---|---|---|
| Strict Interfaces | Type-safe, IDE support | Verbose | Baseline all changes |
| Runtime Validation | Catches runtime errors | Performance cost | Boundary layers |
| Type Guards | TypeScript narrowing | Manual checks | Conditional logic |
| Builder Pattern | Clear intent, validates incrementally | Boilerplate | Complex objects |
| Context Manager | Prevents loss, tracks context | Adds indirection | Multi-step flows |
Recommendation: Use Strict Interfaces + Runtime Validation as foundation, add Type Guards for conditional logic.
Quick Implementation Checklist
See Also
packages/cloudflare-agent/src/types.ts- Current type definitionsapps/telegram-bot/src/transport.ts- Context creation and usagedocs/debug-footer-analysis.md- Context flow in debug footer