My query is about how to return a string[]. Currently, TypeScript is throwing an error because each element of the array has a type of ( T[keyof T] extends readonly (infer InnerArr)[] ? InnerArr : T[keyof T] ). How can I accept the 'property' argument as a string to return string[]? If I just use 'string' instead of keyof T, TypeScript throws an error because it can't identify property in the unknown type on the line item[property].
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);
I attempted to create a variable within the function body and assign the property to it.