Skip to content

Inaccurate Type Definition for String.prototype.matchAll #57024

Description

@kkirby

⚙ Compilation target

ES2020

⚙ Library

es2020.string

Missing / Incorrect Definition

The issue is with the String interface, specifically regarding the matchAll method.

  • Current Incorrect Definition:

    • In the TypeScript standard library file lib.es2020.string.d.ts, the String interface is currently defined as follows:
      interface String {
          matchAll(regexp: RegExp): IterableIterator<RegExpMatchArray>;
      }
    • The return type RegExpMatchArray is only valid for String.prototype.match.
    • String.prototype.matchAll is guaranteed to return an iterator with the same value as RegExp.prototype.exec. The regular expression provided to matchAll must contain the /g modifier, otherwise an error is thrown.
  • Problem with Current Definition:

    • This definition incorrectly says that the index and input properties may not be present in the RegExpMatchArray. However, when using String.prototype.matchAll, it returns an iterator of objects, each consistently including the index and input properties. These properties are not optional in the returned objects.
  • Suggested Correct Definition:

    • The matchAll method should be updated to return IterableIterator<RegExpExecArray>

Sample Code

const str = "Hello, {{name}}!";
for(const match of str.matchAll(/{{(.*?)}}/g)){
  if(match.index > 0){} // TypeScript incorrectly says that `index` may be undefined
}

Documentation Link

https://tc39.es/ecma262/multipage/text-processing.html#sec-string.prototype.matchall

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions