Home > other >  Typescript - iterating in order to parse/refine an Object
Typescript - iterating in order to parse/refine an Object

Time:06-23

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
}

CodePudding user response:

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

  • Related