es-toolkit icon indicating copy to clipboard operation
es-toolkit copied to clipboard

feat(groupBy): update type to return non-empty arrays

Open itsMapleLeaf opened this issue 10 months ago • 4 comments

groupBy is guaranteed to return a non-empty array for each key. Typing it this way allows one to avoid errors under noUncheckedIndexAccess. See here.

itsMapleLeaf avatar Jan 18 '25 18:01 itsMapleLeaf

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
es-toolkit ✅ Ready (Inspect) Visit Preview 💬 Add feedback Jan 18, 2025 7:13pm

vercel[bot] avatar Jan 18 '25 18:01 vercel[bot]

Hey, thanks for the suggestion!

I get that groupBy could return more specific types for non-empty arrays. But since non-empty arrays only guarantee that the first element is non-nullable, anything beyond that (like arr[1] or arr[2]) can still be nullable. Because of that, I wasn’t sure if typing for non-empty arrays would add much value.

Is there a particular use case where returning non-empty arrays helps TypeScript?

raon0211 avatar Jan 30 '25 10:01 raon0211

Hey, thanks for the suggestion!

I get that groupBy could return more specific types for non-empty arrays. But since non-empty arrays only guarantee that the first element is non-nullable, anything beyond that (like arr[1] or arr[2]) can still be nullable. Because of that, I wasn’t sure if typing for non-empty arrays would add much value.

Is there a particular use case where returning non-empty arrays helps TypeScript?

Fair question! It applies in any case where you're indexing the first item off of the value array. See the playground here for an example that a coworker ran into in practice: https://www.typescriptlang.org/play/?noUncheckedIndexedAccess=true#code/CYUwxgNghgTiAEAzArgOzAFwJYHtXwHMYdkAHAIQE8AeAFQBp4BpeEADwxFWAGd4AFYqRAwMlJiEoA+ABQAoePCycAtjwBc8AJKcYUAEYQQdKfQWFiZEZpnKQKzbQCU8ALxTmZp5oBK4HDDA1EyMtADaALpSANxycgDe5mB4PBjwqMhqbhYkFJQyYQCMjABMjADMEYwyqC7u6fAApPAlTrHmiAHwMsmoqTlk8DiI8ADy+gBW4BgAdABuUBDIIDw1mTxOLomKir39C0sgmhkq+iLZRLlhAAwRsYoAvnJPcqCQsAgo6Nh4A3kAcngAKIqUhiOiMFjsTjcPiCHDCUTiSSycx2NSaHQiAxGExmRSXKwwGzoxx1DwhOTeeB+ZKBYKMMIMeAzVnhCJRdrbeB7NInPiuP5UQGoEFg-JFUoVKrdWpuDz4ZqtdqKTowbq8v5DEbjKaYeaLZarfmbeDc3YpNIHZbHTJndWCwmkG53cxPJ5AA

itsMapleLeaf avatar Jan 31 '25 20:01 itsMapleLeaf

Closes https://github.com/toss/es-toolkit/issues/1131

unrevised6419 avatar May 21 '25 22:05 unrevised6419

@raon0211 any objections to this? As @unrevised6419 mentioned above, this would resolve an issue I submitted without seeing that this PR already existed. Without this type change, the DX for us is worse, as we have 1 or 2 scenarios in our app that are pulling the 1st element explicitly.

joealden avatar Oct 03 '25 16:10 joealden