Skip to content

Improve typings for String.split #42330

@asbjornh

Description

@asbjornh

lib Update Request

Configuration Check

My compilation target is ES2015 and my lib is ["dom", "es2019"].
I have noUncheckedIndexedAccess set to true

Missing / Incorrect Definition

String.split

Sample Code

const parts = "a b c".split(" ");
console.log(parts[0].toUpperCase()); // Type error: parts[0] is possibly undefined

Documentation Link

https://tc39.es/ecma262/#sec-string.prototype.split

Description

String.split returns string[]. A return type of [string, ...string[]] would be more useful when noUncheckedIndexedAccess is enabled, sinceString.split will return an array with at least one element in the vast majority of cases.

I'm not completely sure about all of the edge cases here, but as far as I can see there are two cases in which an empty array could be returned:

  • "".split(""), which returns [].
  • Using a splitter function

Given just these two edge cases, it should be pretty straightforward to return [string, ...string[]] when string | RegExp is used as separator:

// lib.es5:
split(separator: "", limit?: number): string[];
split(separator: string | RegExp, limit?: number): [string, ...string[]];

// lib.es2015:
split(splitter: { [Symbol.split](string: string, limit?: number): string[]; }, limit?: number): string[];

I completely understand if you feel like this relies too much on implementation details etc, but I at least wanted to raise the issue because this is annoying me a lot!

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions