Skip to content

String.split, low cost lib modification for narrowing return type of non-empty stringsΒ #56333

Closed as not planned
@craigphicks

Description

@craigphicks

πŸ” Search Terms

#52299 (closed)
#30406 (marked as design limitation)

βœ… Viability Checklist

⭐ Suggestion

In es5.d.ts

before:

interface String {
    split(separator: string | RegExp, limit?: number): string[];
}

after:

interface String {
    split<S extends string>(separator: S): string extends S ? string[] : 
        S extends "" ? string[] : [string, ...string[]];
    split(separator: string | RegExp, limit?: number): string[];
}

πŸ“ƒ Motivating Example

@noUncheckedIndexAccess: true
function checkField(fieldName: string){
    let firstPathPart = fieldName;
    if (fieldName.includes('.')) {
        const partParts = fieldName.split('.');
        firstPathPart = partParts[0]; // error
    }
}

πŸ’» Use Cases

  1. What do you want to use this for?

As shown above

  1. What shortcomings exist with current approaches?

As shown above.

  1. What workarounds are you using in the meantime?
@noUncheckedIndexAccess: true

interface String {
    split<S extends string>(separator: S): string extends S ? string[] : 
        S extends "" ? string[] : [string, ...string[]];
    split(separator: string | RegExp, limit?: number): string[];
}

function checkField(fieldName: string){
    let firstPathPart = fieldName;
    if (fieldName.includes('.')) {
        const partParts = fieldName.split('.');
        firstPathPart = partParts[0]; // no error
    }
}

{
// #53362 & #56332 & #56333 all give these results
const x1 = "".split('.'); // [string, ...string[]]
const x10 = x1[0]; // string
const x11 = x1[1]; // string | undefined
const x31 = "".split('.')[0]; // string
const x32 = "".split('.')[1]; // string | undefined
const x4 = "".split(''); // string[] 
const x5 = "".split((0 as any as string)); // string[]
}

[playground](https://www.typescriptlang.org/play?#code/FDCWDsBcFMCcDMCGBjaACAypWEDmaBvYNEtAZwAcAbUSAHgzWgA8ZwATM87PAPgAoy0ColiJIAe1gAuTAEpZZHuHws2nTGgD83HCoDaAXTSzipc4zXQOXAES3tuvEZNp9SvbgA0aAHT+PZ0NDAG4zEkoaSEFhUXEpRWV8AB80ACVoXABRZgofGgBbWi1ZcABXAoAjOAUnA1DgAF8QeDLwZEhQCXA0ZAALaGQAawAxUGgqdn54ccmAOUQC6ETPOSJzKmhINBnYJQAFcT7D2G2AXh3Z9gWlsPNQeDRpq5voXwhkKjL2aDJ+AHJfP85HJCOFzL1uko0CJTidIFwLjMJtdFm9IrQAUC5HcISRdgcjvC0BdYZB4WR9AAGUJoAD0dLQ4AkTFgsCk4OazWAyCh22YAEYSWh7L4MdFAcCQvTGW5AiofP4xUkjIYeXy0MwAEzCwXU2kMuq4dXgaHMADMwtF4qxwP10sN8uNvNN-IALFbbGLqJj-lKZUajCazQBWT3eqL8fhUtCILiIcAAT1jXCdIIdjKdQaAA)

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