Course contentsShow
← TypeScript
Lesson 1367 of 1,79631. Type-Driven DesignFree lesson

Opaque Types for Units and Measurements

Model domain-specific units like USD, Pixels, or Meters as distinct opaque types.

Opaque Types for Units and Measurements

What you'll learn: How to use opaque types to prevent mixing incompatible units like dollars with euros or pixels with meters at compile time.

The Problem: Primitive Obsession with Units

When modeling measurements or currencies, we typically use primitive numbers:

function transfer(amount: number, from: string, to: string) {
  // ...
}

const usdAmount = 100;
const eurAmount = 85;

transfer(usdAmount, "checking", "savings"); // OK
transfer(eurAmount, "checking", "savings"); // Also OK - but is this right?

All numeric values look the same to TypeScript. Nothing prevents you from accidentally adding USD to EUR, or mixing pixels with percentages in a layout calculation.

Creating Distinct Unit Types with Branding

By applying the branding pattern you learned previously, you can make each unit type structurally distinct:

type USD = number & { readonly __brand: "USD" };
type EUR = number & { readonly __brand: "EUR" };
type Pixels = number & { readonly __brand: "Pixels" };
type Meters = number & { readonly __brand: "Meters" };

Each type is still a number at runtime, but TypeScript treats them as incompatible:

function chargeInUSD(amount: USD) {
  console.log(`Charging $${amount}`);
}

const price: USD = 50 as USD; // Smart constructor would be better
const euros: EUR = 45 as EUR;

chargeInUSD(price);  // ✓ OK
chargeInUSD(euros);  // ✗ Error: EUR is not assignable to USD

Smart Constructors for Units

Instead of manual type assertions, create constructor functions that validate and brand values:

function toUSD(amount: number): USD {
  if (amount < 0) throw new Error("Negative currency amounts not allowed");
  return amount as USD;
}

function toPixels(value: number): Pixels {
  return Math.round(value) as Pixels;
}

const cost = toUSD(29.99);
const width = toPixels(42.7);

This pattern ensures all branded values pass through controlled entry points.

Type-Safe Operations

You can define operations that preserve unit types:

function addUSD(a: USD, b: USD): USD {
  return (a + b) as USD;
}

function multiplyPixels(pixels: Pixels, scale: number): Pixels {
  return (pixels * scale) as Pixels;
}

TypeScript now catches unit mismatches before runtime:

const total = addUSD(toUSD(10), toUSD(20)); // ✓ OK
const mixed = addUSD(toUSD(10), toPixels(20)); // ✗ Type error!

Key Takeaway: Opaque types let you model domain-specific units (USD, Pixels, Meters) as distinct types that prevent accidental mixing, catching unit conversion errors at compile time while remaining plain numbers at runtime.