unacy / Converter
Type Alias: Converter<TInput, TOutput>
type Converter<TInput, TOutput> = (input) => TOutput;Defined in: packages/core/src/converters.ts:52
Unidirectional converter from one unit to another.
A pure function that takes a value tagged with a source unit and returns a value tagged with a destination unit. Converters are registered in the UnitRegistry and composed automatically via BFS when no direct edge exists.
Type Parameters
| Type Parameter | Description |
|---|---|
TInput | Source unit-tagged type (e.g., Celsius) |
TOutput | Destination unit-tagged type (e.g., Fahrenheit) |
Parameters
| Parameter | Type | Description |
|---|---|---|
input | TInput | Value tagged with source unit |
Returns
TOutput
Value tagged with destination unit
Remarks
- Must be a pure function (no side effects, no external state reads)
- Must be deterministic (same input always produces the same output)
- Float arithmetic on chained conversions accumulates rounding error; document precision characteristics in the function's JSDoc
Example
const c2f: Converter<Celsius, Fahrenheit> = (c) => (c * 9/5) + 32;
const f2k: Converter<Fahrenheit, Kelvin> = (f) => ((f - 32) * 5/9) + 273.15;Use When
You need a named, reusable conversion function to pass to registry.register(from, to, converter).
Avoid When
You need both forward and reverse directions — use BidirectionalConverter<A, B> to register both in a single call.
Pitfalls
NEVER mutate the input value inside a converter — because values are primitives or phantom-typed plain objects, mutation is silent and will corrupt the original branded value at the call site.
NEVER rely on closure state inside a converter for caching — the registry caches composed converters by path key, so stateful closures can lead to incorrect results on subsequent calls.
See
- BidirectionalConverter
- RelaxedConverter