Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Your examples has groups only typed as { [key: string]: string }.

It isn't narrowed down to the actual named capture groups inside the regex.

For the whole semver example, we'd want something typed as: { major: string, minor: string, patch: string }.

(sidenote for this semver example and not regex in general: they will be strings because a major of "01" and a patch of "3-prerelease" are both valid. You can parse them into ints later depending on what you're actually doing with the semver)

---

For an example of a type narrowed regex in the ts playground, I'll take the lazy route and point you to an example someone else has made:

https://www.typescriptlang.org/play/?ssl=1&ssc=39&pln=1&pc=3...

You can use a utility library (e.g. ts-regexp, arkregex, etc...), you can use one of the utilities that are shared around the typescript spaces online for the one part you need, or you can make your own utility type.

---

For my use-case, I just want to know that I can change either my code or regex and I'll be alerted before runtime or buildtime if I've forgotten to account for something.

To carry on with the semver example, if a fourth piece of data was added to the incoming string (e.g. product name, build timestamp, build variant, etc...) and I forgot to update both the code and the regex together and instead only updated one, I'd want an alert in my IDE to tell me that I forgot to update the other one.





The ts-regexp package `infer`s out of template literal types to do its magic. That's possible from JSDoc too: https://www.typescriptlang.org/play/?filetype=js#code/PQKhCg...

The behavior of ts-regexp is not especially related to the `RegExpExecArray` type. That package uses unsafe assertions to implement its API.

The only thing that requires TypeScript syntax in the playground you linked is the non-null assertions. Here's that same code in JSDoc mode with the non-null assertions removed (`strictNullChecks` is disabled instead): https://www.typescriptlang.org/play/?filetype=js#code/JYWwDg...

---

> For my use-case, I just want to know that I can change either my code or regex and I'll be alerted before runtime or buildtime if I've forgotten to account for something.

If you can show a concrete example what you want using TypeScript syntax then I'm pretty sure I could port it to JSDoc syntax. (To be clear I'd personally much rather write the TypeScript syntax as I find JSDoc comments annoying & verbose, but they're plenty powerful, being nearly isomorphic to TypeScript annotations.)




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: