Home > database >  type issue when using reduce that adds keys in to an empty object typescript?
type issue when using reduce that adds keys in to an empty object typescript?

Time:01-16

I have this function that reduces an object, my current issue is the I am using reduce on to fill the values of acc[key] to be object[key]; both are erroring out, in code.. I don't want to use any type.

acc[key] Element implicitly has an 'any' type because expression of type'string' can't be used to index type '{}'.

object[key] Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{}'. No index signature with a parameter of type 'string' was found on type '{}'

Playground Link Try

// Reduce Object Immutable !! V2 dont use the delete operator which is slow.
export const reduceObjectImmutable = <T extends object>(
  arr: string[],
  obj: T
) => {
  // make a shallow copy
  const object = { ...obj };
  // get all object keys
  const keys = Object.keys(object);
  // filter keys that are not in the remove array
  const filteredKeys = keys.filter((key) => !arr.includes(key));
  // create new object with filtered keys
  const newObject = filteredKeys.reduce((acc, key) => {
    // Error on both...
    acc[key] = object[key];
    return acc;
  }, {});
  return newObject;
};

CodePudding user response:

I suggest against the object type here and using Record<string, any> instead. You need to then type your initial empty object on your reducer.

// Reduce Object Immutable !! V2 dont use the delete operator which is slow.
export const reduceObjectImmutable = <T extends Record<string, any>>(arr: string[], obj: T): Partial<T> => {
  // make a shallow copy
  const object = { ...obj };
  // get all object keys
  const keys = Object.keys(object);
  // filter keys that are not in the remove array
  const filteredKeys = keys.filter((key) => !arr.includes(key));
  // create new object with filtered keys
  const newObject = filteredKeys.reduce((acc, key) => {
    acc[key] = object[key];
    return acc;
  }, {} as Record<string, any>);
  return newObject as Partial<T>;
};
  • Related