Sub topic 14
Browser, Node.js, and TypeScript Support, Plus a Fallback
This chapter assumes you already know how Object.groupBy and Map.groupBy behave, including the null-prototype result and key coercion. It also assumes you can read a tsconfig.json and run Node.js from a terminal. It covers three things. First, where the methods are available. Second, how TypeScript types them. Third, what to do when your code has to run somewhere they are missing.
Where the Methods Exist
Both methods were standardized in ES2024. Engines shipped them during 2023 and early 2024. The methods became "Baseline" (available in all major browsers) in March 2024, when Safari added them.
| Runtime | First version with both methods | Notes |
|---|---|---|
| Chrome / Edge | 117 | Shipped September 2023 |
| Firefox | 119 | Shipped October 2023 |
| Safari (macOS and iOS) | 17.4 | Shipped March 2024, the last major browser |
| Node.js | 21.0 | Node.js 20 LTS does **not** have them; Node.js 22 LTS does |
| Deno | 1.37 | Uses a V8 version from the same period |
| Bun | 1.1 | Earlier releases may lack `Map.groupBy` |
The Node.js row causes the most trouble. Many servers, CI images, and serverless platforms still run Node.js 18 or 20. On those versions, code that works on your laptop with Node.js 22 fails with this error:
TypeError: Object.groupBy is not a functionYou can check a runtime directly:
node -p "typeof Object.groupBy + ' ' + typeof Map.groupBy"On a supporting version this prints function function. On Node.js 20 it prints undefined undefined.
TypeScript Support
TypeScript has two separate settings that people often confuse. The lib option controls which built-in APIs the type checker knows about. The target option controls which syntax is emitted. Neither one changes what exists at runtime.
Type declarations for both methods arrived in TypeScript 5.4 under the ESNext lib. TypeScript 5.7 added the ES2024 lib and target, which include them. If your lib setting lacks them, the compiler reports:
Property 'groupBy' does not exist on type 'ObjectConstructor'.A configuration for TypeScript 5.7 or later looks like this:
{
"compilerOptions": {
"target": "ES2022",
"lib": ["ES2024", "DOM"],
"module": "NodeNext",
"strict": true
}
}On TypeScript 5.4 to 5.6, use "ESNext" in place of "ES2024". If you list lib yourself, that list replaces the default one, so include "DOM" for browser code.
The Partial Record Return Type
The declaration for Object.groupBy is roughly this:
interface ObjectConstructor {
groupBy<K extends PropertyKey, T>(
items: Iterable<T>,
keySelector: (item: T, index: number) => K,
): Partial<Record<K, T[]>>;
}The return type is Partial, so every group has the type T[] | undefined. That matches the runtime behavior: a key appears only if at least one element produced it. When the callback returns a union of string literals, K narrows to that union. You get autocompletion on group names and still have to handle missing groups:
type Item = {
name: string;
type: "vegetables" | "fruit" | "meat";
quantity: number;
};
const inventory: Item[] = [
{ name: "asparagus", type: "vegetables", quantity: 5 },
{ name: "bananas", type: "fruit", quantity: 0 },
{ name: "cherries", type: "fruit", quantity: 5 },
];
// Type: Partial<Record<"vegetables" | "fruit" | "meat", Item[]>>
const byType = Object.groupBy(inventory, (item) => item.type);
// byType.meat is Item[] | undefined, and here it really is undefined
const meatCount = byType.meat?.length ?? 0;
const fruitNames = (byType.fruit ?? []).map((item) => item.name);
console.log(meatCount); // 0
console.log(fruitNames); // ["bananas", "cherries"]Map.groupBy is typed as returning Map<K, T[]>. Because Map.prototype.get already returns T[] | undefined, you get the same safety without Partial.
A common error is an arrow function that returns a boolean to Object.groupBy. boolean does not satisfy PropertyKey (string | number | symbol), so TypeScript rejects it. That error is the type checker reminding you about key coercion. Either return string keys such as "even" and "odd", or switch to Map.groupBy, which accepts any key type.
Writing a Fallback
When you cannot rely on the runtime, you have three options.
Option 1: core-js
If your build already uses core-js, import just the two modules you need:
import "core-js/actual/object/group-by";
import "core-js/actual/map/group-by";
console.log(typeof Object.groupBy); // "function"These modules install the methods only when they are missing. The core-js versions follow the specification closely, including argument validation.
Option 2: A Local Helper
A helper function (sometimes called a ponyfill) leaves globals untouched. That makes it the safe choice for libraries, because a library should not change built-ins in someone else's application. The version below extends the loop from the earlier chapters. It handles symbol keys and also provides a Map version:
function objectGroupBy(items, keyFn) {
if (typeof keyFn !== "function") {
throw new TypeError("groupBy: callback must be a function");
}
const groups = Object.create(null);
let index = 0;
for (const item of items) {
const key = keyFn(item, index++);
// Match property key conversion: symbols stay symbols, the rest become strings
const propKey = typeof key === "symbol" ? key : String(key);
(groups[propKey] ??= []).push(item);
}
return groups;
}
function mapGroupBy(items, keyFn) {
if (typeof keyFn !== "function") {
throw new TypeError("groupBy: callback must be a function");
}
const groups = new Map();
let index = 0;
for (const item of items) {
const key = keyFn(item, index++);
const group = groups.get(key);
if (group) {
group.push(item);
} else {
groups.set(key, [item]); // Map.set already turns -0 into +0
}
}
return groups;
}
// Prefer the built-in when present
const groupBy = Object.groupBy ?? objectGroupBy;
const groupByToMap = Map.groupBy ?? mapGroupBy;
const parity = groupBy([1, 2, 3, 4], (n) => (n % 2 ? "odd" : "even"));
console.log(parity.odd); // [1, 3]
console.log(Object.getPrototypeOf(parity)); // null
const byBool = groupByToMap([1, 2, 3, 4], (n) => n > 2);
console.log(byBool.get(true)); // [3, 4]Assigning Object.groupBy to a variable and calling it detached is safe. The method is static and does not use this, which you cannot say of most prototype methods.
The for...of loop is what lets the helper accept any iterable, such as strings, Sets, and generators, just like the built-in. A reduce-based fallback works only on arrays unless you convert the input with Array.from first.
Option 3: A Minimal Polyfill
In an application you control, you can install the helpers once at startup so the rest of the code calls the standard names:
function installGroupBy(objectGroupBy, mapGroupBy) {
if (typeof Object.groupBy !== "function") {
Object.defineProperty(Object, "groupBy", {
value: objectGroupBy,
writable: true,
configurable: true,
enumerable: false,
});
}
if (typeof Map.groupBy !== "function") {
Object.defineProperty(Map, "groupBy", {
value: mapGroupBy,
writable: true,
configurable: true,
enumerable: false,
});
}
}Use Object.defineProperty instead of plain assignment. Built-in methods are non-enumerable, and a polyfill should be too, so it does not show up in for...in loops or Object.keys(Object).
Where Hand-Written Fallbacks Differ
The helpers above cover normal use. They still differ from the specification in small ways that rarely matter:
- The built-in collects every key and element before it builds the result. If the callback throws partway through, you get no result in either version, so this matches in practice.
- If an iterator produces more than 2^53 − 1 elements, the built-in throws a
TypeError. The helpers do not check for this. - The helpers use a symbol key as-is and send everything else through
String. For ordinary values this gives the same result as the specification'sToPropertyKey. An object whoseSymbol.toPrimitivemethod returns a symbol is the one edge case where they differ.
TypeScript and Fallbacks Together
If you keep lib below ES2024 because your runtime is older, the compiler will not let you call Object.groupBy directly. A typed local helper keeps things honest:
function groupBy<K extends PropertyKey, T>(
items: Iterable<T>,
keyFn: (item: T, index: number) => K,
): Partial<Record<K, T[]>> {
const groups = Object.create(null) as Partial<Record<K, T[]>>;
let index = 0;
for (const item of items) {
const key = keyFn(item, index++);
(groups[key] ??= []).push(item);
}
return groups;
}
const byLength = groupBy(["a", "bb", "cc"], (s) => (s.length > 1 ? "long" : "short"));
console.log(byLength.long); // ["bb", "cc"]The signature matches the standard declaration. When you later raise lib to ES2024 and your runtimes catch up, you can replace each groupBy( call with Object.groupBy( without changing any types.
Exercise
Your project uses TypeScript 5.7 with "lib": ["ES2024"] and "target": "ES2017". It compiles cleanly, but in production on Node.js 20 it throws "Object.groupBy is not a function". Why didn't the low target fix this, and what are two ways to fix it?
Show answer
The target setting only controls which syntax the compiler emits. It never adds missing library methods. The ES2024 lib told the type checker that Object.groupBy exists, but Node.js 20 does not have it. Fix it by upgrading the runtime to Node.js 22 or later, or by loading a polyfill (core-js/actual/object/group-by, or a small defineProperty-based polyfill) before the code runs. A third option is to use a local helper and lower lib so the compiler stops you from calling the built-in.
Exercise
In TypeScript, const g = Object.groupBy(users, (u) => u.role) where role is "admin" | "guest". Why does g.admin.length fail to compile under strict mode, and how do you read the count safely?
Show answer
Object.groupBy returns Partial<Record<"admin" | "guest", User[]>>, so g.admin has the type User[] | undefined. That type is correct, because the key exists only if some user has that role. Read it with g.admin?.length ?? 0, or use (g.admin ?? []).length.
Exercise
You are publishing an npm library that groups data internally. Should you install a polyfill on Object.groupBy when it is missing? Explain.
Show answer
No. A library should not change globals in the applications that use it. Patching built-ins can conflict with the application's own polyfills or with later spec changes. Use a local helper instead, for example const groupBy = Object.groupBy ?? objectGroupBy. That uses the built-in when it exists and leaves the environment unchanged.