简体   繁体   English

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

[英]How to get distinct values from array in Typescript

I am trying to make well typed function for getting only distinct values of object's property in array.我正在尝试制作类型良好的 function 以便仅获取数组中对象属性的不同值。 So it works like that所以它是这样工作的

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')

so function needs to detect possible keys for seconds argument (that I've managed to do) and type of the value (I don't know how to do this one)所以 function 需要检测秒参数的可能键(我已经设法做到了)和值的类型(我不知道该怎么做)

Here is my function这是我的 function

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[] ??????????

So Typescript cannot figure it out that res should be string[] instead of this I am getting here unknown[] .所以 Typescript 无法弄清楚res应该是string[]而不是这个我到这里unknown[] How can I fix it?我该如何解决?

As far as I can tell, the ArrayObject definition and function return type are not correct.据我所知, ArrayObject定义和 function 返回类型不正确。

This will work:这将起作用:

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)[]

The important part is to define your property as a keyof T , and the return type as the type associated with that property ( T[K] ), or in this case, an array of that type ( T[K][] ).重要的部分是将您的属性定义为keyof T ,并将返回类型定义为与该属性关联的类型( T[K] ),或者在这种情况下,定义为该类型的数组( T[K][] )。


TypeScript Playground link TypeScript 游乐场链接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM