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.
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];
}
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.