typescript 57 lines · 10 steps

Checking WCAG color contrast in TypeScript

Parse hex colors, compute relative luminance, and test the contrast ratio against WCAG thresholds.

Explained by highlit
1type RGB = { r: number; g: number; b: number };
2 
3type WCAGLevel = "AA" | "AAA";
4type TextSize = "normal" | "large";
5 
6function parseHex(hex: string): RGB {
7 const normalized = hex.replace(/^#/, "").trim();
8 const full = normalized.length === 3
9 ? normalized.split("").map((c) => c + c).join("")
10 : normalized;
11 
12 if (!/^[0-9a-fA-F]{6}$/.test(full)) {
13 throw new Error(`Invalid hex color: ${hex}`);
14 }
15 
16 return {
17 r: parseInt(full.slice(0, 2), 16),
18 g: parseInt(full.slice(2, 4), 16),
19 b: parseInt(full.slice(4, 6), 16),
20 };
21}
22 
23function relativeLuminance({ r, g, b }: RGB): number {
24 const [rl, gl, bl] = [r, g, b].map((channel) => {
25 const s = channel / 255;
26 return s <= 0.03928 ? s / 12.92 : Math.pow((s + 0.055) / 1.055, 2.4);
27 });
28 return 0.2126 * rl + 0.7152 * gl + 0.0722 * bl;
29}
30 
31function contrastRatio(foreground: string, background: string): number {
32 const l1 = relativeLuminance(parseHex(foreground));
33 const l2 = relativeLuminance(parseHex(background));
34 const [lighter, darker] = l1 > l2 ? [l1, l2] : [l2, l1];
35 return (lighter + 0.05) / (darker + 0.05);
36}
37 
38function meetsWCAG(
39 foreground: string,
40 background: string,
41 level: WCAGLevel = "AA",
42 size: TextSize = "normal",
43): { ratio: number; passes: boolean; required: number } {
44 const ratio = contrastRatio(foreground, background);
45 const thresholds: Record<WCAGLevel, Record<TextSize, number>> = {
46 AA: { normal: 4.5, large: 3 },
47 AAA: { normal: 7, large: 4.5 },
48 };
49 const required = thresholds[level][size];
50 return {
51 ratio: Math.round(ratio * 100) / 100,
52 passes: ratio >= required,
53 required,
54 };
55}
56 
57export { contrastRatio, meetsWCAG, parseHex };
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Contrast is a ratio of relative luminances, not a simple difference of colors.
  2. 2Encoding valid options as string-literal unions lets a typed lookup table replace scattered conditionals.
  3. 3Normalizing and validating input at the boundary keeps the math functions clean and total.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Checking WCAG color contrast in TypeScript — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code