unacy / BidirectionalConverter
Type Alias: BidirectionalConverter<TInput, TOutput>
type BidirectionalConverter<TInput, TOutput> = {
from: Converter<TOutput, TInput>;
to: Converter<TInput, TOutput>;
};Defined in: packages/core/src/converters.ts:116
Bidirectional converter with forward and reverse transformations.
Registers both directions in a single registry.register(A, B, converter) call. Under the hood, the registry splits { to, from } into two unidirectional edges in the adjacency map.
Remarks
- Round-trip conversions should preserve value within acceptable floating-point tolerance; test with
Math.abs(parse(format(x)) - x) < epsilon - Both converters must be deterministic pure functions
Example
const celsiusFahrenheit: BidirectionalConverter<Celsius, Fahrenheit> = {
to: (c) => (c * 9/5) + 32,
from: (f) => (f - 32) * 5/9
};
const registry = createRegistry().register(CelsiusMeta, FahrenheitMeta, celsiusFahrenheit);
registry.Celsius.to.Fahrenheit(0 as Celsius); // 32
registry.Fahrenheit.to.Celsius(32 as Fahrenheit); // 0Use When
Both conversion directions are commonly needed and you want to minimise the number of register calls.
Avoid When
Only one direction is needed — registering both wastes a graph edge and slightly enlarges the type-level union. Use a plain Converter and call register once.
Pitfalls
NEVER swap to and from in the object literal — the names are just conventions; the registry trusts the object structure, so a transposed pair silently registers the wrong direction for each edge.
NEVER assume chained round-trips are exact — floating-point rounding means from(to(x)) may differ from x by epsilon; use toleranced comparisons.
See
- Converter
- RelaxedBidirectionalConverter
Type Parameters
| Type Parameter | Description |
|---|---|
TInput | First unit type (the "from" direction) |
TOutput | Second unit type (the "to" direction) |
Properties
| Property | Type | Description | Defined in |
|---|---|---|---|
from | Converter<TOutput, TInput> | Reverse converter (TOutput → TInput) | packages/core/src/converters.ts:118 |
to | Converter<TInput, TOutput> | Forward converter (TInput → TOutput) | packages/core/src/converters.ts:117 |