logoalt Hacker News

spartanatreyulast Monday at 2:18 AM2 repliesview on HN

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"?


Replies

matt_kantorlast Monday at 5:09 PM

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...
show 1 reply
g947olast Monday at 2:21 AM

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.