Regrettably, the typings in @types/core-js
have not been updated since 2021, meaning they do not cover information about the group()
array method.
Fortunately, we typically do not need to depend on these typings. Features that make it to Stage 3 of the TC39 Process are usually directly integrated into TypeScript when you set the --target
compiler option to "ESNext"
.
However, there is an issue with the compatibility of the proposed group
and groupToMap
methods, which are currently in Stage 3 but face a naming conflict as detailed in tc39/proposal-array-grouping#44. It is likely that TypeScript will delay support until this issue is resolved.
On the bright side, you can take matters into your own hands if you don't want to wait. If you are comfortable using group
even though it may be renamed, you are free to merge your own types for it into the global Array<T>
interface in your codebase. Just remember to use module declarations and declare global
if necessary. For more insights, check out Is @types/core-js still necessary for TS typings in a Node.js project?.
If official typings are unavailable, you'll need to create your own. Here's a possible example:
// declare global { // maybe
interface Array<T> {
group<K extends PropertyKey>(
callbackfn: (value: T, index: number, array: T[]) => K,
thisArg?: any
): { [P in K]?: T[] };
groupToMap<K>(
callbackfn: (value: T, index: number, array: T[]) => K,
thisArg?: any
): Map<K, T[]>;
}
// }
Once you've imported the required polyfills, TypeScript should allow you to use them without issues:
const array = [1, 2, 3, 4, 5];
const g = array.group((num, index, array) => {
return num % 2 === 0 ? 'even' : 'odd';
});
/* const g: {
even?: number[] | undefined;
odd?: number[] | undefined;
} */
console.log(g)
/* {
odd: [1, 3, 5],
even: [2, 4]
}
*/
const odd = { odd: true };
const even = { even: true };
const m = array.groupToMap((num, index, array) => {
return num % 2 === 0 ? even : odd;
});
/* const m: Map<{ odd: boolean; } | { even: boolean; }, number[]> */
console.log(m)
/* Map (2) {
{ odd: true } => [1, 3, 5],
{ even: true } => [2, 4]
} */
Playground link to code