Skip to content

Units of Measure

Type-safe physical units with compile-time dimensional analysis. Catch dimension mismatches before runtime.

Quick Start

bash
npm install @typesugar/units
typescript
import { meters, seconds, kilograms } from "@typesugar/units";

const distance = meters(100);
const time = seconds(10);
const velocity = distance.div(time); // Type: Unit<Velocity> (m/s)

Type-Safe Arithmetic

typescript
const d1 = meters(100);
const d2 = meters(50);
const t = seconds(10);

// Same-unit operations work
const total = d1.add(d2); // ✓ 150 meters

// Different-unit operations caught at compile time
const invalid = d1.add(t); // ✗ Compile error

Available Units

Base Units

CategoryUnits
Lengthmeters, kilometers, centimeters, feet, inches, miles
Masskilograms, grams, milligrams, pounds
Timeseconds, minutes, hours, days, milliseconds

Derived Units

UnitDimensions
VelocitymetersPerSecond, kilometersPerHour
AccelerationmetersPerSecondSquared
Forcenewtons (kg·m/s²)
Energyjoules (kg·m²/s²)
Powerwatts (J/s)

Unit Literals

typescript
import { units } from "@typesugar/units";

const speed = units`100 km/h`; // Type: Unit<Velocity>
const mass = units`5.5 kg`; // Type: Unit<Mass>

Conversion

Use .to() with a unit constructor to convert between units of the same dimension:

typescript
import { kilometers, meters, feet, hours, minutes } from "@typesugar/units";

const d = kilometers(1);
d.to(meters); // Unit(1000, "m")
d.to(feet); // Unit(~3280.84, "ft")

const t = hours(2);
t.to(minutes); // Unit(120, "min")

// Type-safe: can't convert across dimensions
// d.to(minutes);  // ✗ Compile error

.to() takes a unit constructor function (e.g., meters, feet) — not a string.

How It Works

Dimensions are tracked at the type level:

typescript
meters(1); // Unit<Dimensions<1, 0, 0, ...>>  (length=1)
seconds(1); // Unit<Dimensions<0, 0, 1, ...>>  (time=1)

// meters / seconds:
// Unit<Dimensions<1, 0, -1, ...>>  (length=1, time=-1 = velocity)

Learn More

Released under the MIT License.