pixiebrix / pixiebrix-extension

PixieBrix browser extension
https://www.pixiebrix.com
GNU Affero General Public License v3.0
83 stars 22 forks source link

Improve RegEx typings #6628

Open grahamlangford opened 9 months ago

grahamlangford commented 9 months ago

_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

github-actions[bot] commented 5 months ago

This issue will be closed in 7 days unless the stale label is removed, or a comment is added to the issue.

grahamlangford commented 5 months ago

Nice to have but low priority. Keeping alive for now.

github-actions[bot] commented 2 months ago

This issue will be closed in 7 days unless the stale label is removed, or a comment is added to the issue.

fregante commented 1 month ago

TS 5.5 will start parsing/validating regexes so this might eventually become part of TS itself.

https://devblogs.microsoft.com/typescript/announcing-typescript-5-5/#regular-expression-syntax-checking

This is not yet available though:

https://www.typescriptlang.org/play/?target=10#code/MYewdgzgLgBATgUwOYIB4wLwwPQApcD8APKADakLBQCW4AcgIYC2CAfAHQBUAlADrvcChIggoswUAJJgAJmla8ZAam7YA3ACgNoSLCbUIEamCSZ4yNOzSVcpEMAY1w7ABaIAZoPZI4IAK4ADhAE7HQA8gAKAKIaMHHY2DAAegQaQA