我的问题是如何返回一个字符串数组。现在 TypeScript 抛出了错误,因为在数组的每个元素中,类型是 (T[keyof T] extends readonly (infer InnerArr)[] ? InnerArr : T[keyof T])。我该如何接受 'property' 参数作为字符串来返回 string[] 类型的结果?如果我只是将 keyof T 替换为字符串,TypeScript 会在 item[property] 这一行抛出错误,因为它在 unknown 类型中无法识别 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);
尝试过在函数体内部创建一个变量并赋值给它传递进来的 property。