I want to create a generic map function that takes any type object as first argument and one prefix string as second argument that will be concatenated to object's property name with same value and returns this new created object.
1 Answer
Related question
Consider this exmaple:
type Remap<Obj, Prefix extends string> = {
[Prop in keyof Obj as `${Prefix}${Prop & string}`]: Obj[Prop]
}
const map = <Obj, Prefix extends string>(obj: Obj, prefix: Prefix) =>
(Object.keys(obj) as Array<keyof Obj & string>).reduce((acc, elem) => ({
...acc,
[`${prefix}${elem}`]: obj[elem]
}), {} as Remap<Obj, Prefix>)
const result = map({
one: 1,
two: 2,
three: 3
}, 'set_')
result.set_one //
result.set_two
See key-remapping
I have used as type asserion because this is the only way to go in this particular case
1 Comment
samadadi
Thank you. I appreciate your help.