ts-union
ts-union copied to clipboard
Comparison to https://github.com/practical-fp/union-types
-
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 , 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:
-
union-types
has transparent types for union values, e.g. you "know" that they havetag
andvalue
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. -
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')