Parse hex colors with template literal types
TypeScript
// Hex color strings are constrained by a template literal type and parsed.
type HexColor = `#${string}`;
type Rgb = readonly [red: number, green: number, blue: number];
function parseHex(color: HexColor): Rgb {
let hex = color.slice(1);
if (hex.length === 3) hex = [...hex].map((char) => char + char).join('');
if (hex.length !== 6 || !/^[0-9a-f]+$/i.test(hex)) {
throw new TypeError(`invalid hex color: ${color}`);
}
return [
parseInt(hex.slice(0, 2), 16),
parseInt(hex.slice(2, 4), 16),
parseInt(hex.slice(4, 6), 16),
];
}
function withAlpha(color: HexColor, alpha = 1): string {
const [red, green, blue] = parseHex(color);
return `rgba(${red}, ${green}, ${blue}, ${alpha})`;
}
const brand: HexColor = '#4f8';
console.log(withAlpha(brand)); // rgba(68, 255, 136, 1)