I've encountered an issue with a function that is meant to reduce an object. The problem lies in using the reduce method to assign the values of acc[key] as object[key], which is resulting in errors in the code. I am trying to avoid using any specific 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;
};