I'm using a core-js polyfill for the new group Array method that is proposed to be added to ECMAScript.
I'm importing the polyfill globally using:
import 'core-js/actual/array/group'
I use the method with this line in an api call where I'm grouping the items by username.
const imagesByUser = imageResponse.items.group(({ username }) => username);
The method runs fine and returns the expected output but I get a vscode error on this line saying: Property 'group' does not exist on type 'DetailedImageResponse[]'.ts(2339)
I've installed the @types/core-js package but that hasn't resolved the issue. How can I update the Array prototype type information to include polyfills?
Unfortunately, the typings in @types/core-js
have not been touched since 2021 and therefore do not include information about the group()
array method.
But fortunately, we usually don't have to rely on such typings anyway; proposed features that reach Stage 3 of the TC39 Process are usually added directly to TypeScript and available when you set the --target
compiler option to "ESNext"
.
But unfortunately, while the proposal to add group
and groupToMap
is currently (as of 2023-04-13) in Stage 3, there is a compatibility issue with the name group
, as described in tc39/proposal-array-grouping#44, and it will probably have to be renamed or moved elsewhere, and so TypeScript will almost certainly wait to support it.
But fortunately, you don't have to wait for this if you don't want to. If you're comfortable using group
even though it's going to be renamed, you should feel free to merge your own types for it into the global Array<T>
interface in your code base. (And if your code is in a module you will need to declare global
to do this. (Also see Is @types/core-js still necessary for TS typings in a Node.js project?)
Without an official typing you'll have to come up with one yourself. Possibly like this:
// 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[]>;
}
// }
And then, assuming you've imported the appropriate polyfills, TypeScript should let you use them without error:
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]
} */