Skip to content

Improve string split return type of first array index #53362

Open
@zardoy

Description

@zardoy

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

split(separator: string | RegExp, limit?: number): string[];

Essentially duplicate of #49635, but with #49635 (comment) 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 #49682, which significantly improved type-checking experience by using less exclamation marks

Metadata

Metadata

Assignees

No one assigned

    Labels

    Awaiting More FeedbackThis means we'd like to hear from more people who would be helped by this featureSuggestionAn idea for TypeScript

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions