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.