my question is – how return a string[]. Right now TS throw error because every element of array is type of ( T[keyof T] extends readonly (infer InnerArr)[] ? InnerArr : T[keyof T] )
How do i accept ‘property’ argument as a string for return string[]. If i just write string instead keyof T, TS throw error because on the line item[property] TS can’t see propert in unknown type.
interface IMovie {
genre: string[];
actors: string[];
}
const movies: IMovie[] = [
{
genre: ['Action', 'Sci-Fi', 'Adventure'],
actors: ['Scarlett Johansson', 'Florence Pugh', 'David Harbour'],
}
];
function collectByProperty<T>(arr: T[], property: keyof T): string[] {
const array = arr.map((item) => item[property]).flat();
const elem = array[0];
const final = [...new Set(array)];
return final;
}
const genres = collectByProperty<IMovie>(movies, 'genre');
const actors = collectByProperty<IMovie>(movies, 'actors');
console.log(genres);
console.log(actors);
Tried to create variable in function body and write in it property.
2
Answers
Use
flatMap
instead ofmap
thenflat
:You need to flatten the array in your collectByProperty function because it initially produces an array of arrays (like
[['Action', 'Sci-Fi'], ['Drama']]
). Flattening this converts it into a single-level array (['Action', 'Sci-Fi', 'Drama']
), matching the expected output.