Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Reading a property of generic type in nested function

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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; })[].

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading