How would you use a template literal type to validate that a string matches a specific structured pattern, like a hex color code?
Short answer
Build a template literal type describing the exact expected character pattern using nested unions for each character position — while genuinely complex patterns (like arbitrary-length hex codes) hit practical limits, simpler fixed-length patterns work well and give real…
Advertisement
AModel answer
Build a template literal type describing the exact expected character pattern using nested unions for each character position — while genuinely complex patterns (like arbitrary-length hex codes) hit practical limits, simpler fixed-length patterns work well and give real compile-time format validation.
type HexDigit = '0'|'1'|'2'|'3'|'4'|'5'|'6'|'7'|'8'|'9'|'a'|'b'|'c'|'d'|'e'|'f';
type HexColor = `#${HexDigit}${HexDigit}${HexDigit}${HexDigit}${HexDigit}${HexDigit}`;
const valid: HexColor = '#ff5733'; // OK
// const invalid: HexColor = '#zzz'; // Error: doesn't match patternReal-world example
Enforcing that a configuration value or design-token color string is a syntactically valid 6-digit hex code at compile time.
Likely follow-ups
- Why does this specific approach become impractical for validating longer or more complex patterns, like full email address validation?
Related topics