pixiebrix-extension icon indicating copy to clipboard operation
pixiebrix-extension copied to clipboard

Improve RegEx typings

Open grahamlangford opened this issue 2 years ago • 4 comments

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 RegExp instead of regex literals, so we'd lose syntax highlighting, etc

https://blog.ndpsoftware.com/2022/10/strong-typing-regexp

grahamlangford avatar Oct 10 '23 14:10 grahamlangford