0

This is a followup to this question: Maintain object value types for each key when reassigning values This creates an error:

const obj = {
    a: 1,
    b: 'foo',
};

for (const k of (Object.keys(obj) as (keyof typeof obj)[])) {
    obj[k] = obj[k];
}

To fix it, I could use generics and forEach:

(Object.keys(obj) as (keyof typeof obj)[])
    .forEach(<T extends keyof typeof obj>(k: T) => {
        obj[k] = obj[k];
    });

Is there a way to use generics with a for loop? I'm not using forEach anywhere else in my codebase and I'd like to keep it consistent. Also, I don't want to define a separate (non-anonymous) function, since forEach would be cleaner.

TS Playground: https://www.typescriptlang.org/play?#code/MYewdgzgLgBCBGArGBeGBvAUDHMCGAXDAIwA02u8RA5AGYgjXkC+A3JpvQE4wAUokWAGs4tPgHkkAU2BQAdEKkBPCLwSIAlPgh9FSkGKhKADlINwkGgNoBdDVqy4LiK0Jupnrm+2YdekxBl5PVV1LTwdXj1zI1NzMNsNChw5bgBRPGAAC14AHgAVGCkADygpMAATHWjDEzMxdQA+KKJ8rRRGjGSnTzcPdS92J2YNViA

1 Answer 1

0

That is not possible. TypeScript is not smart enough to detect that accessing it and assigning it is allowed in this case. The only thing you can do is to add a @ts-ignore comment above that line:

const obj = {
    a: 1,
    b: 'foo',
};

for (const k of (Object.keys(obj) as (keyof typeof obj)[])) {
    // @ts-ignore
    obj[k] = obj[k];
}

https://www.typescriptlang.org/play?#code/MYewdgzgLgBCBGArGBeGBvAUDHMCGAXDAIwA02u8RA5AGYgjXkC+A3JpvQE4wAUokWAGs4tPgHkkAU2BQAdEKkBPCLwSIAlPgh9FSkGKhKADlINwkGgNoBdDVqy4YAemcwAAlAgBaAJYBzMBAuKQocdSshG1QLREibdmZMIA

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.