Skip to content

Overloads for String.prototype.split method #61816

Closed as not planned
Closed as not planned
@EzioMercer

Description

@EzioMercer

⚙ Compilation target

ES2020

⚙ Library

lib.es5.d.ts

Missing / Incorrect Definition

It is not wrong definition, but if it is possible, I would like to suggest add overloads for String.prototype.split method

I like to use string template types instead of just string as much as possible, and it works like a charm. The problem is that when I try to split my well-known string, it returns just string[] type which isn't very descriptive

My suggestion is to add simple overloads:

  1. When the separator is string and limit is not provided or undefined
  2. When the separator is string | RegExp and limit is 0

I added zero to the list because it is straightforward to implement that case, but if it means that I also should provide type checking for negative values, noninteger values and correct tuple splitting type then forget about it 😁

We can completely remove limit from overloads. I added it just to get the same type for provided limit as undefined and not provided limit otherwise the return type will be string[] if the value of limit is undefined

Sample Code

type Split<Source extends string, Separator extends string> = Source extends `${infer Left}${Separator}${infer Right}`
    ? [...(string extends Left ? string[] : [`${Left}`]), ...Split<Right, Separator>]
    : Source extends ""
      ? Separator extends ""
          ? []
          : [""]
      : string extends Source
        ? string[]
        : [Source];

interface String {
    split<Source extends string, Separator extends string>(
        this: Source,
        separator: Separator,
        limit?: undefined,
    ): Split<Source, Separator>;

    split(separator: string | RegExp, limit: 0): [];
}

You can see types in action on playground (with examples)

Documentation Link

No response

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