Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

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

for (const variable in object) {
    // Statement execution
}

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.
const config = { host: "localhost", port: 8080 };

for (const key in config) {
    // TS Error: Element implicitly has an 'any' type because expression 
    // of type 'string' can't be used to index type '{ host: string; port: number; }'.
    const value = config[key]; 
}
To resolve this strict typing constraint, the iteration variable must be explicitly asserted as a key of the target object type:
for (const key in config) {
    // Safe property access using type assertion
    const typedKey = key as keyof typeof config;
    const value = config[typedKey]; 
}

Prototype Filtering

To prevent the loop from processing inherited properties, the execution block is typically guarded using Object.prototype.hasOwnProperty.call().
for (const key in object) {
    if (Object.prototype.hasOwnProperty.call(object, key)) {
        // Execution is restricted to the object's own enumerable properties
    }
}
Master TypeScript with Deep Grasping Methodology!Learn More