2

I am trying to parse an object to refine the unnecessary data - in this case I get an error at rtn[key], and I have no understanding of why. Please read the tl;dr for some more context and thanks in advance;

type TValueCar = { make: { value: string }; model: { value: string } };
type TCarKey = keyof TValueCar;
type TCar = { make: { value: string }; model: { value: string } };

const parseCarValueObject = (valueObject: TValueCar): TCar => {
  const ObjectKeys = Object.keys(valueObject) as TCarKey[];

  const rtn = {} as TCar;
  ObjectKeys.forEach((key) => {
    rtn[key] = valueObject[key].value;
  });

  return rtn;
};

tl;dr I am hoping to create a generic version of this function, and this is the first stage in my attempt. I realise that there is an easier way of solving this which doesn't would be very simple but wouldn't be helpful in my attempt to create the generic function. [Extract below]

const rtn = {
    make:valueObject.make.value,
    model:valueObject.model.value
}

1 Answer 1

2

In this line

rtn[key] = valueObject[key].value;

You are trying to assign the string of value from valueObject to the type TCar that expects an object of type { value: "something" }, this is why you're getting this error.

try to simply remove the access to value in order to assign the whole object to your rtn variable.

const parseCarValueObject = (valueObject: TValueCar): TCar => {
  const ObjectKeys = Object.keys(valueObject) as TCarKey[];

  const rtn = {} as TCar;
  ObjectKeys.forEach((key) => {
    // It should works now
    rtn[key] = valueObject[key];
  });

  return rtn;
};

See the example on typescript playground

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

1 Comment

Thanks, this has worked now. My error was actually just writing TCar incorrectly it should have been type TCar = { make: string; model: string }; but either way you have cleared things up for me. Thanks @Yago Biermann

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.