Reputation: 42474
I need to create a generic helper method, which
id
isActive
propertyhere 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.
Upvotes: 2
Views: 26
Reputation: 4484
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; })[]
.
Upvotes: 2