TS 5.4:Object.groupBy 和 Map.groupBy 方法添加了類型聲明
2 月 22 日,TypeScript 團(tuán)隊(duì)發(fā)布了 TypeScript 5.4 RC 版本。即將發(fā)布的 TypeScript 5.4 為 Object.groupBy 和 Map.groupBy 方法添加了類型聲明。
通過(guò)以下命令,你就可以體驗(yàn)最新的 TypeScript 5.4 RC 版本:
npm install -D typescript@rc
本文我將介紹 Object.groupBy 和 Map.groupBy 這兩個(gè)方法,需要注意的是,你需要把 tsconfig.json 文件中 target 屬性配置成 esnext 才訪問(wèn)這些方法。
{
"compilerOptions": {
"target": "esnext",
}
}
Object.groupBy()
Object.groupBy() 靜態(tài)方法會(huì)根據(jù)提供的回調(diào)函數(shù)返回的字符串值對(duì)給定可迭代的元素進(jìn)行分組。該方法的類型定義如下:
// typescript/lib/lib.esnext.object.d.ts
interface ObjectConstructor {
/**
* Groups members of an iterable according to the return value of the passed callback.
* @param items An iterable.
* @param keySelector A callback which will be invoked for each item in items.
*/
groupBy<K extends PropertyKey, T>(
items: Iterable<T>,
keySelector: (item: T, index: number) => K,
): Partial<Record<K, T[]>>;
}
在以上代碼中,K 和 T 是泛型變量,其中 K extends PropertyKey 是泛型約束,PropertyKey 是一個(gè)聯(lián)合類型:
type PropertyKey = string | number | symbol;
而 Partial 和 Record 是 TypeScript 內(nèi)置的工具類型。由 groupBy 的類型定義可知,參數(shù) keySelector 是函數(shù)類型,包含 item 和 index 兩個(gè)參數(shù)。
下面,我們將使用 Object.groupBy() 方法,對(duì)數(shù)組中的對(duì)象進(jìn)行分組:
const inventory = [
{ name: "asparagus", type: "vegetables", quantity: 5 },
{ name: "bananas", type: "fruit", quantity: 0 },
{ name: "goat", type: "meat", quantity: 23 },
{ name: "cherries", type: "fruit", quantity: 5 },
{ name: "fish", type: "meat", quantity: 22 },
];
const groupedByType = Object.groupBy(inventory, ({ type }) => type);
Map.groupBy()
Map.groupBy() 靜態(tài)方法使用提供的回調(diào)函數(shù)返回的值對(duì)給定可迭代的元素進(jìn)行分組。最終返回的 Map 使用測(cè)試函數(shù)中的唯一值作為鍵,可用于獲取每個(gè)組中的元素?cái)?shù)組。該方法的類型定義如下:
interface MapConstructor {
/**
* Groups members of an iterable according to the return value of the passed callback.
* @param items An iterable.
* @param keySelector A callback which will be invoked for each item in items.
*/
groupBy<K, T>(
items: Iterable<T>,
keySelector: (item: T, index: number) => K,
): Map<K, T[]>;
}
在以上代碼中,K 和 T 是泛型變量。調(diào)用該方法后,會(huì)返回 Map 類型的對(duì)象。與 Object.groupBy 靜態(tài)方法一樣,參數(shù) keySelector 也是函數(shù)類型,包含 item 和 index 兩個(gè)參數(shù)。
下面我們來(lái)看一下如何使用 Map.groupBy() 方法對(duì)數(shù)組中的對(duì)象進(jìn)行分組:
const inventory = [
{ name: 'asparagus', type: 'vegetables', quantity: 6 },
{ name: 'bananas', type: 'fruit', quantity: 16 },
{ name: 'goat', type: 'meat', quantity: 20 },
{ name: 'cherries', type: 'fruit', quantity: 12 },
{ name: 'fish', type: 'meat', quantity: 8 },
];
const result = Map.groupBy(inventory, ({ quantity }) =>
quantity < 10 ? "restock" : "sufficient",
);
const restock = result.get("restock");
const sufficient = result.get("sufficient");