microsoft / microsoft/TypeScript

Type named capture groups better

Offen
#32,098 22 Kommentare 106 Reaktionen 0 zugewiesene Personen Auf GitHub ansehen

Dieses Issue hat noch niemand übernommen.

Awaiting More Feedback Suggestion
Vorherrschende Sprache
Go
Sterne
111k
Forks
14.3k
Ø Merge
2 T. 4 Std.
Gemergte PRs (30 T.)
132

Beschreibung

Search Terms

named regexp, named capture groups

Motivation

Currently named capture groups are a bit of a pain in TypeScript:

  1. All names are of type string even if the regexp doesn't have that named group.
  2. You need to use non-null assertion for .groups even when that is the only possibility.

Suggestion

I propose making RegExp higher order on its named capture groups so that .groups is well typed.

// Would have type: RegExp<{ year: string, month: string }>
const date = /(?<year>[0-9]{4})-(?<month>[0-9]{2})/

const match = someString.match(date)
if (match) {
  // match.groups type would be { year: string, month: string }
  // currently is undefined | { [key: string]: string }
}

// Would have type RegExp<{ year: string, month?: string }>
const optionalMonth = /(?<year>[0-9]{4})(-(?<month>[0-9]{2}))?/

Checklist

My suggestion meets these guidelines:

  • [✓] This wouldn't be a breaking change in existing TypeScript/JavaScript code
  • [✓] This wouldn't change the runtime behavior of existing JavaScript code
  • [✓] This could be implemented without emitting different JS based on the types of the expressions
  • [✓] This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, etc.)
  • [✓] This feature would agree with the rest of TypeScript's Design Goals.

Beitragsleitfaden

Beitragsleitfaden öffnen

Erste Schritte

  1. Lies das ganze Issue und danach den Beitragsleitfaden des Projekts.
  2. Schreib ins Issue, dass du es übernimmst — das erspart doppelte Arbeit.
  3. Forke das Repository und arbeite in einem Branch.
  4. Öffne einen Pull Request, der die Issue-Nummer nennt.

Rechercherichtung

Das Issue nennt keine Implementierungsdateien oder Tests. Beginne damit zu prüfen, wie RegExp und Match-Gruppen derzeit typisiert werden, und ermittle dann, ob benannte Gruppen wie vorgeschlagen abgeleitet werden können; abgeschlossen ist die Aufgabe, wenn benannte und optionale Capture-Gruppen genau dargestellt werden, ohne das erzeugte JavaScript zu ändern.

Vom Indexierungsmodell aus dem Issue-Text verfasst.

Bewertung

Tech-Stack
javascript, typescript
Bereich
compilers
Issue-Typ
Feature
Schwierigkeit
5/5
Geschätzter Aufwand
Über eine Woche
Aktivitätsstatus
Veraltet
Klarheit
Größtenteils klar
Anfängerfreundlichkeit
25/100

Neue Issues direkt in Ihr Postfach

Eine kurze Übersicht über anfängerfreundliche GitHub-Issues.