Home > other >  Reading a property of generic type in nested function
Reading a property of generic type in nested function

Time:11-14

I need to create a generic helper method, which

  • can accept array of any object but at least it should have id
  • return a new array of object where each one has isActive property

here is my code

export const useActionLinks = <T,>(
  data: T & { id: string }[]
) => {
  let active = '';

  function mapper(d: T) {
    return {
      ...d,
      isActive: d.id === active, // Error id does not exist on type T
    };
  }
  const itemsData = data.map(mapper); // Error
  console.log(itemsData);
};

But ts is complaining at 2 points one at function mapper and second at data.map call.

CodePudding user response:

It works with a few changes to your types.

export const useActionLinks = <T extends {id: string}>(
  data: T[]
) => {
  let active = '';

  function mapper(d: T) {
    return {
      ...d,
      isActive: d.id === active, // Error id does not exist on type T
    };
  }
  const itemsData = data.map(mapper); // Error
  console.log(itemsData);
  return itemsData
};


useActionLinks([
    {a:1, id:"s"}, {b:2, id:'p'}
])

The first change is on the first line. I changed your generic to extend the base object with id. This will fix both errors. You don't need to explicitly mention the return type since it's automatically inferred as (T & { isActive: boolean; })[].

  • Related