如何从Typescript中的数组中获取不同的值

时间:2020-07-22 09:40:57

标签: arrays typescript distinct-values

我正在尝试创建类型正确的函数,以仅获取数组中对象属性的不同值。这样就可以了

type Employee = { work: WorkEnum; name: string };
const arg1: Employee[] = [{ name: "kornad", work: WorkEnum.Doctor}, { name: "Adam", work: WorkEnum.FrontEndDeveloper}]

const result1: WorkEnum[] = getDistinct(arg1, 'work')
const result1: string[] = getDistinct(arg1, 'name')

因此函数需要检测可能的秒参数(我设法做到)的键和值的类型(我不知道该怎么做)

这是我的职能

type ArrayObject<V> = {
  [key: string]: V;
};

function getDistinct<V, T extends ArrayObject<V>>(
  data: T[],
  property: keyof T
): V[] {
  const allValues = data.reduce((values: V[], current) => {
    if (current[property]) {
      values.push(current[property]);
    }
    return values;
  }, []);

  return [...new Set(allValues)];
}

const arrayOfData: { xxx: string; qwe: string | number }[] = [
  { xxx: 'asd', qwe: 43 },
  { xxx: 'asd', qwe: 'dsadas' },
];

const res = getDistinct(arrayOfData, 'xxx'); // res: unknown[], why not string[] ??????????

所以Typescript无法弄清楚res应该是string[]而不是这个,我在这里是unknown[]。我该如何解决?

1 个答案:

答案 0 :(得分:1)

据我所知,ArrayObject定义和函数返回类型不正确。

这将起作用:

function getDistinct<T, K extends keyof T>(data: T[], property: K): T[K][] {
  const allValues = data.reduce((values: T[K][], current) => {
    if (current[property]) {
      values.push(current[property]);
    }
    return values;
  }, []);

  return [...new Set(allValues)];
}

const arrayOfData: { xxx: string; qwe: string | number }[] = [
  { xxx: 'asd', qwe: 43 },
  { xxx: 'asd', qwe: 'dsadas' },
];

const res1 = getDistinct(arrayOfData, 'xxx'); // string[]
const res2 = getDistinct(arrayOfData, 'qwe'); // (string | number)[]

重要的部分是将您的属性定义为keyof T,并将返回类型定义为与该属性关联的类型(T[K]),或者在这种情况下,将其定义为一个数组({ {1}}。


TypeScript Playground link