Skip to content

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

Open
@joshkel

Description

@joshkel

⚙ Compilation target

es2022

⚙ Library

lib.es2024.object

Missing / Incorrect Definition

The type definitions for Object.groupBy<K, T> state that it returns a Partial<Record<K, T>>. This is useful if K is a union, enum, etc. - the result is is likely Partial, and the result is consistent with a Partial<Record<K, T>> 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<string | number, T> literal than a Partial<Record<string | number, T>> literal, and any mistakes are more consistently dealt with using TypeScript's noUncheckedIndexedAccess option.

See #56805 (comment) and #56805 (comment) from the PR that originally added types for Object.groupBy.

Sample Code

type Employee = { name: string, role: 'ic' | 'manager' };
const employees: Set<Employee> = 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

Metadata

Metadata

Assignees

No one assigned

    Labels

    Awaiting More FeedbackThis means we'd like to hear from more people who would be helped by this featureSuggestionAn idea for TypeScript

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions