microsoft / microsoft/TypeScript

`Object.groupBy` should not return `Partial<Record<string, T>>` or `Partial<Record<number, T>>`

Open
#61,706 7 comments 11 reactions 0 assignees View on GitHub
Awaiting More Feedback Suggestion
Dominant language
Go
Stars
111k
Forks
14.3k
PR merge metrics
PR metrics pending

Description

### ⚙ Compilation target

es2022

### ⚙ Library

lib.es2024.object

### Missing / Incorrect Definition

The type definitions for `Object.groupBy` state that it returns a `Partial>`. This is useful if `K` is a union, enum, etc. - the result is is likely `Partial`, and the result is consistent with a `Partial>` literal, and having `Partial` helps prevent mistakes from assuming that every key is present in the resulting record. However, it's unnecessary if `K` is a unrestricted number or string: there's no way that a declared key within the result can have an `undefined` value, and the result is more consistent with a `Record` literal than a `Partial>` literal, and any mistakes are more consistently dealt with using TypeScript's `noUncheckedIndexedAccess` option.

See https://github.com/microsoft/TypeScript/pull/56805#issuecomment-2196526425 and https://github.com/microsoft/TypeScript/pull/56805#issuecomment-2385027658 from the PR that originally added types for `Object.groupBy`.

### Sample Code

```TypeScript
type Employee = { name: string, role: 'ic' | 'manager' };
const employees: Set = new Set();

const byName = Object.groupBy(employees, x => x.name);
for (const [name, nameGroup] of byName) {
// TypeScript gives an error that nameGroup may be undefined,
// but it's always defined
console.log(nameGroup.length);
}
```

### Documentation Link

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/groupBy

Contributor guide

Open the contributing guide

Research direction

Start in the lib.es2024.object declarations and inspect the current Object.groupBy type, then find the corresponding library declaration tests. Check how unrestricted string and number keys differ from union or enum keys, and run the relevant TypeScript tests. Done means the broad key cases no longer produce Partial while union-like keys retain appropriate optionality.

Written by the indexing model from the issue text.

Assessment

Tech stack
javascript, typescript
Domain
compilers
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Quiet
Clarity
Mostly clear
Newbie friendliness
56/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.