es-toolkit
es-toolkit copied to clipboard
feat(groupBy): update type to return non-empty arrays
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.
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 |
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?
Hey, thanks for the suggestion!
I get that
groupBycould 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 (likearr[1]orarr[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
Closes https://github.com/toss/es-toolkit/issues/1131
@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.