Skip to content

@devhaven/unit-conversion

@devhaven/unit-conversion is a lightweight, zero-dependency TypeScript library for converting measurements across physical and numerical domains. It provides a fluent, chainable API that enforces category-level type safety at compile time.

Compile-Time Type Safety

TypeScript automatically narrows .to() to units in the same category as .from(), catching incompatible conversions (like meter to celsius) before your code runs.

Zero Dependencies

Built with pure TypeScript and standard JavaScript APIs. Works out of the box in Node.js, Bun, Deno, edge runtimes, and modern browsers.

Fluent & Callable API

Call your converter instance directly with convert(100) or use convert.value(100), passing either number or numeric string inputs.

Precision & Locale Formatting

Customize decimal precision (decimals), toggle integer rounding (isFloat), or format numbers for any region with locale.

import { Conversion } from "@devhaven/unit-conversion";
const convert = new Conversion();
// Convert 100 meters → kilometers
const { value, unit } = convert(100).from("meter").to("kilometer");
console.log(value, unit);
// 0.1, "km"
// Customize precision and locale formatting
const formatted = new Conversion({ decimals: 3, locale: "en-US" });
const distance = formatted(5280).from("foot").to("meter");
console.log(`${distance.value} ${distance.unit}`);
// "1,609.344 m"

When you select a unit in .from(), TypeScript infers the unit category (UnitCategory<F>) and restricts .to() to valid target units within that same category:

import { Conversion } from "@devhaven/unit-conversion";
const convert = new Conversion();
// Valid: both "celsius" and "fahrenheit" belong to TemperatureUnits
convert(100).from("celsius").to("fahrenheit"); // { value: 212, unit: "°F" }
// TypeScript compile-time error:
// Argument of type '"kilogram"' is not assignable to parameter of type 'TemperatureUnits'.
convert(100).from("celsius").to("kilogram");

@devhaven/unit-conversion supports 9 measurement categories out of the box. Each category converts values through a standard base unit:

CategoryBase UnitSupported Units
Lengthmeter (m)millimeter, centimeter, meter, kilometer, inch, foot, yard, mile
Temperaturekelvin (K)celsius, fahrenheit, kelvin
Weightgram (g)milligram, gram, kilogram, ounce, pound, ton
Volumeliter (l)milliliter, liter, cubic-meter, cubic-foot, cubic-inch, us-legal-cup, imperial-cup, us-liquid-pint, imperial-pint, imperial-fluid-ounce
Timesecond (s)millisecond, second, minute, hour, day, week
Numberdecimaldecimal, binary, base8 (octal), hexadecimal
Pressurepascal (Pa)pascal, kilopascal, bar, psi, atmosphere
Energyjoule (J)joule, kilojoule, calorie, calorie-international-table, calorie-thermochemical, watt-hour, kilowatt-hour, electron-volt
Forcenewton (N)newton, dyne, poundal, pound-force, kilogram-force