Remix.run Logo
spartanatreyu a day ago

Not that person, but is there an easy way to write something like a basic semver?

export type SemVer = `${number}.${number}.${number}`;

Could you extend it to work with regex groups like:

export const SemVerRegex = /^(?<major>0|[1-9]\d)\.(?<minor>0|[1-9]\d)\.(?<patch>0|[1-9]\d)(?:-((?:0|[1-9]\d|\d[a-zA-Z-][0-9a-zA-Z-])(?:\.(?:0|[1-9]\d|\d[a-zA-Z-][0-9a-zA-Z-]))))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$/;

Could the groups be extracted so you the type back if you ran the regex on a string like: "1.2.3", or "1.2.3-prerelease"?

matt_kantor 17 hours ago | parent | next [-]

I don't understand the second part of your comment (that's a value, not a type), but the first part looks like this:

    /** @typedef {`${number}.${number}.${number}`} SemVer */
Here's a playground: https://www.typescriptlang.org/play/?filetype=js#code/PQKhAI...
spartanatreyu 10 hours ago | parent [-]

Thanks for the example, I had a good play around with it.

The second part of my comment is a value yes, but it's implicitly typed by typescript automatically. I was asking about how to use that type (and it's internals) in jsdoc.

matt_kantor 7 hours ago | parent [-]

> it's implicitly typed by typescript automatically

What do you mean by this? Can you share an example?

Regular expressions do not act as type guards, and there's no way to express a type that allows one regular expression but rejects another (they're all just `RegExp`): https://www.typescriptlang.org/play/?target=5#code/MYewdgzgL...

spartanatreyu 3 hours ago | parent [-]

You wouldn't use `test()` like in your example.

`test()` only returns a boolean, you want to look at `exec()` which returns the result of the regular expression (typed as: `RegExpExecArray | null` which you can narrow down to `RegExpExecArray` by checking if the result is null or not).

RegExpExecArray gives you a structure that looks different between the jsdoc version and the typescript version.

The typescript version has `.groups` inside RegExpExecArray.

You can use that as is, or you can add some extra type utilities to extract the named groups from inside the regex. (If you look inside typescript's issues on github you'll find a whole bunch of them that people have wanted typescript to include by default).

There's a few regex PRs to add extraction and syntax checking to typescript by default, but they're delayed until after the compiler switch from ts to go. (but there's porting to go in the PRs anyway).

g947o a day ago | parent | prev [-]

it is possible to do many of these with @typedef, but it gets difficult with JSDoc very quickly. In TypeScript you can easily create multi-line type aliases. Not quite so in JSDoc.