microsoft / microsoft/TypeScript

Improve string split return type of first array index

Open
#53,362 10 comments 6 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Awaiting More Feedback Suggestion
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

https://github.com/microsoft/TypeScript/blob/b70784ef8f3ba3fd21750b9acf275dd7edcc7fe7/src/lib/es5.d.ts#L460

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

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split#description (note)

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

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. 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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.