[英]How to get distinct values from array in Typescript
我正在嘗試制作類型良好的 function 以便僅獲取數組中對象屬性的不同值。 所以它是這樣工作的
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')
所以 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[] ??????????
所以 Typescript 無法弄清楚res
應該是string[]
而不是這個我到這里unknown[]
。 我該如何解決?
據我所知, ArrayObject
定義和 function 返回類型不正確。
這將起作用:
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]
),或者在這種情況下,定義為該類型的數組( T[K][]
)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.