Skip to content

String#matchAll should return iterable of RegExpExecArray instead of RegExpMatchArray #36788

@ZhangYiJiang

Description

@ZhangYiJiang

TypeScript Version: 3.7 (issue is with lib typing)

Search Terms: regex, matchall, es2020

Code

const matches = Array.from('xxx'.matchAll(/x/g));
matches[0].index; // TS reports index may be undefined, when it should always be defined

Currently matchAll returns an iterable of RegExpMatchArray. However, the index and input properties on RegExpMatchArray are optional because String#match returns a match object without those if the regex has the global flag (#35157).

matchAll on the other hand doesn't have the same behavior, so it should use RegExpExecArray where both of those properties are non-optional (or maybe create a RegExpMatchAllArray type)

> Array.from('xxx'.matchAll(/x/g)) 
[
  [ 'x', index: 0, input: 'xxx', groups: undefined ],
  [ 'x', index: 1, input: 'xxx', groups: undefined ],
  [ 'x', index: 2, input: 'xxx', groups: undefined ]
]
> Array.from('xxx'.matchAll(/a/g)) 
[]
> Array.from('aaa'.matchAll(/x/g)) 
[]

Expected behavior:

input and index on the match objects are not optional

Actual behavior:

TS reports that input and index may be optional

Playground Link: (Can't use playground since lib cannot be configured)

Related Issues: #30936 introduced String#matchAll

Metadata

Metadata

Assignees

No one assigned

    Labels

    BugA bug in TypeScript

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions