Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

array.groupBy potentially results in incorrect return type #829

Open
fatton139 opened this issue Nov 15, 2024 · 0 comments
Open

array.groupBy potentially results in incorrect return type #829

fatton139 opened this issue Nov 15, 2024 · 0 comments

Comments

@fatton139
Copy link

fatton139 commented Nov 15, 2024

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!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant