Skip to content Skip to sidebar Skip to footer

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);
}

Playground link

Post a Comment for "Maintain Object Value Types For Each Key When Reassigning Values"