How would you use template literal types to enforce a semantic-versioning-style string format at compile time?
Short answer
Build a template literal type combining number-embedding for each version segment with literal '.' separators, giving reasonable structural validation of the major.minor.patch shape — though note this can't validate that each segment stays within a specific numeric RANGE, since…
Advertisement
AModel answer
Build a template literal type combining number-embedding for each version segment with literal '.' separators, giving reasonable structural validation of the major.minor.patch shape — though note this can't validate that each segment stays within a specific numeric RANGE, since 'number' embedded in a template literal accepts any numeric string.
type SemVer = `${number}.${number}.${number}`;
const valid: SemVer = '1.4.2'; // OK
// const invalid: SemVer = '1.4'; // Error: missing the patch segmentReal-world example
Enforcing that a package version string field follows the expected major.minor.patch structural shape before it's used elsewhere.
Likely follow-ups
- Why can't this technique alone prevent an invalid value like '99999.0.0' if there's a business rule against versions that high?
Related topics