Skip to content

RegExpMatchArray index 0 incorrectly possibly undefined when noUncheckedIndexedAccess is enabledΒ #42296

Closed
@DetachHead

Description

@DetachHead

Bug Report

πŸ”Ž Search Terms

RegExpMatchArray noUncheckedIndexedAccess

πŸ•— Version & Regression Information

4.2.0-dev.20210112

  • This is the behavior in every version I tried, and I reviewed the FAQ for entries about noUncheckedIndexedAccess

⏯ Playground Link

Playground link with relevant code

πŸ’» Code

const foo = "".match(/a/)
if (foo !== null) {
    const bar: string = foo[0] //Type 'string | undefined' is not assignable to type 'string'
}

πŸ™ Actual behavior

index 0 is of type string|undefined

interface RegExpExecArray extends Array<string> {
    index: number;
    input: string;
}

πŸ™‚ Expected behavior

index 0 should be of type string, since RegExpMatchArray will always have at least one value in it as when no matches are found, it returns null instead. see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match#return_value

therefore we can be confident that if a RegExpMatchArray is returned, it will always have a length of at least 1

should be something like this:

type RegExpMatchArray = [string] & string[] & {
    index?: number;
    input?: string;
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    Needs ProposalThis issue needs a plan that clarifies the finer details of how it could be implemented.SuggestionAn idea for TypeScript

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions