array.groupBy potentially results in incorrect return type

Author: fatton139Created Nov 15, 2024Updated Aug 18, 2026
Labelsp2: type enhancementnext major

Grouping by a key that may not exist results makes the return type of Record<K, T[]> potentially incorrect.

Extending the docs example https://es-toolkit.slash.page/reference/array/groupBy.html:

type Grocery = {
    category: "fruit" | "vegetable" | "meat",
    name: string
}

const array: Grocery[] = [
  { category: 'fruit', name: 'apple' },
  { category: 'fruit', name: 'banana' },
  { category: 'vegetable', name: 'carrot' },
];
const result = groupBy(array, item => item.category);
// result will be:
// {
//   fruit: [
//     { category: 'fruit', name: 'apple' },
//     { category: 'fruit', name: 'banana' }
//   ],
//   vegetable: [
//     { category: 'vegetable', name: 'carrot' }
//   ]
// }
// No meat in the result

const sortMeat = (meat: {category: "meat", name: string}[]) => meat.sort(() => 0)

// Cannot read properties of undefined (reading 'sort') 
sortMeat(result.meat)

Lodash's return type for groupby is Partial<Record<K, T[]>> which could be appropriate here if you're after parity.

Thanks!