javascript 如何返回字符串[]?

yquaqz18  于 9个月前  发布在  Java
关注(0)|答案(2)|浏览(109)

我的问题是-如何返回一个字符串[].现在TS抛出错误,因为数组的每个元素都是类型(T[keyof T] extends readonly(inferent InnerArr)[]?InnerArr:T[keyof T])我如何接受'property'参数作为返回字符串[]的字符串.如果我只是写字符串而不是keyof T,TS抛出错误,因为行项目[property] TS无法看到未知类型的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);

字符串
尝试在函数体中创建变量并写入其属性。

lmvvr0a8

lmvvr0a81#

使用flatMap代替map,然后使用flat

const array = arr.flatMap((item) => item[property]);

字符串

shyt4zoc

shyt4zoc2#

您需要在collectByProperty函数中flatten数组,因为它最初会生成一个数组数组(如[['Action', 'Sci-Fi'], ['Drama']])。将其flatten转换为一个单层数组(['Action', 'Sci-Fi', 'Drama']),匹配预期的输出。

相关问题