microsoft / microsoft/TypeScript
Improve string split return type of first array index
Nobody has claimed this yet.
- Dominant language
- Go
- Stars
- 111k
- Forks
- 14.3k
- Avg merge
- 1d 19h
- Merged PRs (30d)
- 117
Description
lib Update Request
Please, consider improving user experience for "".split(...) in cases when string literal is passed, which I believe most users do e.g. split(' ') or split('\n')
Configuration Check
My compilation target is ES2015 and my lib is the default.
Missing / Incorrect Definition
Essentially duplicate of https://github.com/microsoft/TypeScript/issues/49635, but with https://github.com/microsoft/TypeScript/issues/49635#issuecomment-1163047914 handled:
split<T extends string | RegExp>(separator: T, limit?: number): T extends `${string}${infer U}` ? [string, ...string[]] : string[];
And this should added to param JSDoc then: Only passing `""` and `new RegExp("")` values can result in returning an empty array.
Sample Code
This is super inconvenient when used with destructure:
const [firstLine, ...restLine] = str.split('\n')
// firstLine is possibly undefined, need add exclamation marks everywhere or `as [string, ...string]` above
I also wanted to do the same for when regexp literal is passed e.g. split(/\n\r?/) as only split(new RegExp('')) can result in empty array (if I'm not mistaken), which I believe no one does, but the literal value can't be captured anyway
Documentation Link
P.S. I remembered of this issue after https://github.com/microsoft/TypeScript/pull/49682, which significantly improved type-checking experience by using less exclamation marks
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start with the String.split declaration in src/lib/es5.d.ts around line 460, then review the related issue #49635 and its referenced comment. Done means the type distinguishes literal nonempty separators as returning a nonempty-first-element tuple, while preserving the empty-array cases and documenting those cases in the parameter JSDoc.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- javascript, typescript
- Domain
- compilers
- Issue type
- Feature
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Active
- Clarity
- Mostly clear
- Newbie friendliness
- 48/100