简体   繁体   中英

Using generics in a for loop in Typescript

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM