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.

A for loop in TypeScript is a control flow statement used to execute a block of code repeatedly based on a boolean condition or over an iterable data structure. TypeScript enhances standard JavaScript loops by enforcing static typing, type inference, and strict scope management on loop variables, iterators, and collections.

Standard for Loop

The traditional for loop consists of three optional expressions: initialization, condition, and afterthought. TypeScript allows explicit type annotations within the initialization block, though it typically infers the type.
for (let i: number = 0; i < 5; i++) {
    console.log(i);
}
  • Initialization (let i: number = 0): Declares the loop counter. Block-scoped to the loop.
  • Condition (i < 5): Evaluated before each iteration. Must resolve to a truthy/falsy value.
  • Afterthought (i++): Executed at the end of each iteration.

for...of Loop

The for...of statement iterates over the values of iterable objects (such as Array, Map, Set, and String). TypeScript automatically infers the type of the loop variable based on the type of the iterable.
const sequence: number[] = [10, 20, 30];

for (const value of sequence) {
    // 'value' is implicitly typed as 'number'
}
When iterating over complex types like Tuples, TypeScript infers the loop variable as a union type of the tuple’s elements:
const mixedTuple: [string, number, boolean] = ["text", 42, true];

for (const item of mixedTuple) {
    // 'item' is typed as 'string | number | boolean'
}

for...in Loop

The for...in statement iterates over the enumerable string properties (keys) of an object. In TypeScript, the loop variable in a for...in loop is always inferred as a string, regardless of the object’s key types, because JavaScript coerces all object keys to strings at runtime.
const registry: Record<string, boolean> = { active: true, pending: false };

for (const key in registry) {
    // 'key' is implicitly typed as 'string'
    const value: boolean = registry[key]; 
}
Note: TypeScript compiler options (like noImplicitAny) will enforce strict indexing rules when using the string key to access object properties within the loop body.

Type Narrowing in Loops

TypeScript performs control flow analysis within loop bodies. If a loop variable is a union type, you can use type guards to narrow the type for specific operations.
const data: (string | number)[] = ["a", 1, "b", 2];

for (const element of data) {
    if (typeof element === "string") {
        // 'element' is narrowed to 'string'
        element.toUpperCase();
    } else {
        // 'element' is narrowed to 'number'
        element.toFixed(2);
    }
}
Master TypeScript with Deep Grasping Methodology!Learn More