pixiebrix-extension
pixiebrix-extension copied to clipboard
Improve RegEx typings
Originally posted by @fregante in https://github.com/pixiebrix/pixiebrix-extension/pull/6607#discussion_r1349465899
I thought of an alternative way to define/use groups: with a helper function that forces us to define the regex and its expected groups next to its definition:
// before const elementsCollectionRegexp = /((?<collectionName>.*)\.)?(?<elementIndex>\d+)/; // after const elementsCollectionRegexp = regexGroups<[ 'collectionName', 'elementIndex' ]>(/((?<collectionName>.*)\.)?(?<elementIndex>\d+)/)Still not fail-safe, but:
- it's easier to tell if they become mismatched
- there's no need for
!/assert- it enforces the property names at the usage site.
There's a less verbose way, but it requires using
new RegExpinstead of regex literals, so we'd lose syntax highlighting, etchttps://blog.ndpsoftware.com/2022/10/strong-typing-regexp