Typescript'te boş bir nesneye anahtar ekleyen reduce kullanırken tip sorunu mu?


Elimde bir nesneyi azaltan bir fonksiyon var, mevcut sorunum, acc[key] değerlerini object[key] ile doldurmak için reduce kullanıyorum; ikisi de kodda hata veriyor.. herhangi bir tür kullanmak istemiyorum.

acc[key] Eleman, türü '{}' olan bir indeksi kullanamayacağından dolayı ifadedeki 'string' türü nedeniyle üstü kapalı olarak 'any' türüne sahiptir.

object[key] Öğe, türü '{}' olan bir indeksi işaretlemek için 'string' türünde bir ifade kullanılamayacağı için üstü kapalı olarak 'any' türüne sahiptir. '{}' türünde 'string' türünde bir parametreye sahip bir indeks imzası bulunamadı

Oyun Alanı Bağlantısını Deneyin

// 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;
};

Cevap #1

Burada object türü yerine Record<string, any> kullanmanızı öneriyorum. Daha sonra azaltıcınızda başlangıçtaki boş nesneyi bunu tür olarak belirtmeniz gerekiyor.

// 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>;
};