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 { NestFactory } from '@nestjs/core'; import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger'; import { ValidationPipe } from '@nestjs/common'; import { ApiProperty } from '@nestjs/swagger';
Wiring validation and Swagger docs in NestJS
validation
openapi
decorators
Intermediate
8 steps
typescript
import { Component, Input } from '@angular/core'; interface Order { id: string;
How Angular ICU plurals localize an order summary
i18n
pluralization
standalone-component
Intermediate
8 steps
typescript
import { Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common'; import { Observable, catchError, concatMap, finalize } from 'rxjs'; import { DataSource, QueryRunner } from 'typeorm';
Wrapping requests in a transaction with NestJS
interceptors
transactions
rxjs
Advanced
7 steps
typescript
type CsvColumn<T> = { header: string; value: (row: T) => string | number | boolean | null | undefined; };
Building a type-safe CSV writer in TypeScript
generics
serialization
escaping
Intermediate
7 steps
typescript
import { parsePhoneNumberFromString, CountryCode } from 'libphonenumber-js'; export interface NormalizedPhone { e164: string;
Normalizing phone numbers to E.164 in TypeScript
validation
normalization
error-handling
Intermediate
7 steps
php
<?php namespace App\Http\Controllers;
Broadcasting typing indicators in Laravel
websockets
authorization
presence-channels
Intermediate
9 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.