1

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 1

2

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

Playground

See key-remapping

I have used as type asserion because this is the only way to go in this particular case

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. I appreciate your help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.