I am trying to create a function that lets a caller remap an object given a specific mapping. The resulting object should be able to know the new new field names and types.
Is this possible in typescript? I think all I need at this point is a return type. This is non-working code I have:
const mapping = {
a: "learn",
b: "state"
}
const original = {
a: false,
b: 0
}
const map = <
Mapping,
Original
>(
mapping: Mapping,
states: Original
): {
[key: Mapping[key]]: Original[key] //WHAT IS THE CORRECT TYPE HERE?
} => {
return Object.keys(original).reduce((total, key) => {
return {
...total,
[mapping[key]]: original[key] //THERE IS AN ERROR HERE TOO BUT I AM NOT WORRIED ABOUT THAT RIGHT NOW
}
}, {})
}
const remapped = map(mapping, original)
console.log(remapped)
console.log(remapped.learn)
console.log(remapped.state)
I am essentially trying to rename a
to learn
and b
to state
. The code is working functionally but I am getting a type error ('key' refers to a value, but is being used as a type here.). Any help would be greatly appreciated!