ts-union icon indicating copy to clipboard operation
ts-union copied to clipboard

Comparison to https://github.com/practical-fp/union-types

Open janwirth opened this issue 2 years ago • 1 comments

  • I'm submitting a ... [x] question about the decisions made in the repository [x] question about how to use this project

  • Summary Why should I use this library over the other one?

janwirth avatar Dec 03 '21 11:12 janwirth

@janwirth , I haven't looked at https://github.com/practical-fp/union-types. It looks pretty awesome, thanks!

There are two things that came to my mind:

  1. union-types has transparent types for union values, e.g. you "know" that they have tag and value fields. While ts-union purposefully makes internal data structure opaque. Look at my comment here https://github.com/twop/ts-union/issues/6#issuecomment-534393616 for more details.
  2. matchWith function that allows to match a tuple of unions. Even though I'm still not happy with the final API (hence experimental), I still think that it is a killer feature, at least for my use cases. It comes in handy if you are modeling transitions in Elm(ish) architecture pattern.

Here is the example from README

import { Union, of } from 'ts-union';

const State = Union({
  Loading: of(null),
  Loaded: of<number>(),
  Err: of<string>(),
});

const Ev = Union({
  ErrorHappened: of<string>(),
  DataFetched: of<number>(),
});

const { Loaded, Err, Loading } = State;

const transition = State.matchWith(Ev, {
  Loading: {
    ErrorHappened: (_, err) => Err(err),
    DataFetched: (_, data) => Loaded(data),
  },

  Loaded: {
    DataFetched: (loaded, data) => Loaded(loaded + data),
  },

  default: (prevState, ev) => prevState,
});

// usage
const newState = transition(Loading, Ev.ErrorHappened('oops')); // <-- State.Err('oops')

twop avatar Dec 04 '21 19:12 twop