iterate-objects-safely
Installation
SKILL.md
Know How to Iterate Over Objects
Overview
Iterating over objects in TypeScript is surprisingly tricky. The for...in loop infers keys as string rather than the object's keys, leading to indexing errors. This happens because objects can have additional properties beyond their declared type (structural typing), and for...in includes inherited properties.
Understanding safe iteration patterns helps you avoid any types and type assertions while correctly handling object traversal.
When to Use This Skill
- Iterating over object keys and values
for...inloops produce "Element implicitly has 'any' type" errorsObject.entriesreturnsanyvalue types- Need to handle both known and unknown object properties
- Considering Map vs object for data storage
The Iron Rule
Use Object.entries for safe iteration over any object. Use for...in with keyof assertions only when you know the exact shape. Consider Map for guaranteed type safety.