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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Contrast is a ratio of relative luminances, not a simple difference of colors.
- 2Encoding valid options as string-literal unions lets a typed lookup table replace scattered conditionals.
- 3Normalizing and validating input at the boundary keeps the math functions clean and total.
Related explainers
typescript
import { registerLocaleData } from '@angular/common'; import localeFr from '@angular/common/locales/fr'; import localeFrExtra from '@angular/common/locales/extra/fr'; import localeDe from '@angular/common/locales/de';
Locale-aware bootstrapping in Angular
i18n
localization
dependency-injection
Intermediate
8 steps
typescript
import { Module } from '@nestjs/common'; import { ConfigModule } from '@nestjs/config'; import * as Joi from 'joi';
Validating env config at boot in NestJS
configuration
schema-validation
environment-variables
Intermediate
8 steps
php
<?php namespace App\Services\Checkout;
Validating coupons with Laravel's Pipeline
pipeline
chain of responsibility
transactions
Intermediate
7 steps
typescript
import { Inject, Injectable, Logger } from '@nestjs/common'; import { CACHE_MANAGER } from '@nestjs/cache-manager'; import { Cache } from 'cache-manager'; import { InjectRepository } from '@nestjs/typeorm';
A cache-aside country lookup in NestJS
cache-aside
dependency-injection
batch-lookup
Intermediate
8 steps
php
<?php namespace App\Services;
How a password strength validator works in PHP
validation
regular-expressions
data-driven
Intermediate
8 steps
typescript
import { Injectable, effect, signal, computed } from '@angular/core'; interface Preferences { theme: 'light' | 'dark';
A signal-based preferences store in Angular
signals
state-management
persistence
Intermediate
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/checking-wcag-color-contrast-in-typescript-explained-typescript-607e/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.