Home > Enterprise >  Add type information during array destructing in a loop
Add type information during array destructing in a loop

Time:10-27

Does typescript allow type annotations in for...of loops? Either something like this for array destructuring

for(let [id, value]: [string, number] of Object.entries(some_object)) { }

Or something like this for object destructuring:

for(let {a, b}: {a: string, b: number} of arr) { }

Note: Specifically asking about the case where some_object and arr either do not have type information or have incomplete type information.

CodePudding user response:

To get the correct types without a separate let in the body of the loop (as suggested by SharedRory), you can fix the type of the array you are iterating over by casting it.

const arr = [{a: 'a' as unknown, b: 2 as unknown}];

for(let {a, b} of arr) { 
    // No types in here b is unknown.
     a.b;
}

for(let {a, b} of arr as {a: string, b: number}[]) { 
    // Yes types here, b is a string
     a.replace("a", "");
}

Link to playground

  • Related