Skip to main content
The for...in statement is a control flow construct that iterates over all enumerable string properties (keys) of an object, including those inherited through its prototype chain. In TypeScript, it operates fundamentally as an object property enumerator rather than a collection iterator.

Syntax

Technical Characteristics

  • Type Inference: TypeScript implicitly types the iteration variable as a string. Even if an object’s keys are defined as numbers or specific string literals in the type definition, the for...in loop extracts them as generic strings at runtime.
  • Prototype Traversal: The loop does not strictly evaluate the target object’s own properties. It traverses the entire prototype chain, yielding any enumerable properties inherited from ancestor objects.
  • Array Behavior: When applied to an Array, the loop yields the array indices as string types (e.g., "0", "1") along with any custom enumerable properties attached to the array object. Iteration order is implementation-dependent and not guaranteed to be sequential.

TypeScript Indexing Constraints

Because TypeScript infers the loop variable as a generic string, using it to access object values via bracket notation often results in an implicit any type error (TS7053) if the object lacks a string index signature.
To resolve this strict typing constraint, the iteration variable must be explicitly asserted as a key of the target object type:

Prototype Filtering

To prevent the loop from processing inherited properties, the execution block is typically guarded using Object.prototype.hasOwnProperty.call().
Tired of Poor TypeScript Skills? Fix That With Deep Grasping!Learn More