4 ms·
Typescript can do Maybe and Either, but it's a little verbose because you have to manage the tags yourself. For instance you can certainly do: type Maybe<
by dllthomas 5y ago
Typescript can do Maybe and Either, but it's a little verbose because you have to manage the tags yourself.
For instance you can certainly do:
type Maybe<X> = { tag: 'just', value: X } | { tag: 'nothing'};
type Either<X, Y> = { tag: 'left', value: X } | { tag: 'right', value: Y };
function either<X, Y, Z>(fromLeft: (x: X) => Z, fromRight: (y: Y) => Z, xy: Either<X, Y>): Z {
switch (xy.tag) {
case 'left': return fromLeft(xy.value);
case 'right': return fromRight(xy.value);
}
}
Note that this is meaningfully different from the (often more idiomatic and certainly less verbose) untagged use of union types because you can distinguish left from right even when the contained types agree and you can distinguish different nestings, for better and for worse.