Skip to content

unacy / BidirectionalConverter

Type Alias: BidirectionalConverter<TInput, TOutput>

ts
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

typescript
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); // 0

Use 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 ParameterDescription
TInputFirst unit type (the "from" direction)
TOutputSecond unit type (the "to" direction)

Properties

PropertyTypeDescriptionDefined in
fromConverter<TOutput, TInput>Reverse converter (TOutput → TInput)packages/core/src/converters.ts:118
toConverter<TInput, TOutput>Forward converter (TInput → TOutput)packages/core/src/converters.ts:117

Released under the MIT License.