Maintain Object Value Types For Each Key When Reassigning Values
const obj = { a: 1, b: 'foo', }; for (const k of (Object.keys(obj) as (keyof typeof obj)[])) { obj[k] = obj[k]; } TS Playground: https://www.typescriptlang.org/play?#
Solution 1:
Here is one way, using generics to get the key as a typeK instead of as a runtime value k:
const obj = {
a: 1,
b: 'foo',
};
function set<K extends keyof typeof obj>(k : K) {
obj[k] = obj[k];
}
for (const k of (Object.keys(obj) as (keyof typeof obj)[])) {
set(k);
}
Post a Comment for "Maintain Object Value Types For Each Key When Reassigning Values"