unsplash / sum-types-io-ts

io-ts bindings for @unsplash/sum-types.
https://unsplash.github.io/sum-types-io-ts/
MIT License
2 stars 1 forks source link

Aliased tagged sums / map multiple tags #24

Open samhh opened 1 year ago

samhh commented 1 year ago

It may be useful to be able to alias tags, nullary or not. This'd be somewhat equivalent to Serde's alias attribute. An example use case:

type Weather = Sum.Member<"Sun"> | Sum.Member<"Rain">
type Country
  = "UK" // Rain
  | "Italy" // Sun
  | "Spain" // Sun

It's possible with getCodecFromMappedNullaryTag however that's not terribly ergonomic, and it's undocumented what should happen when multiple members of one type map to a single member of the other.

samhh commented 1 year ago

I wonder if we could cheaply support this by extending getCodecFromPrimitiveMappedNullaryTag to support regex:

getCodecFromPrimitiveMappedNullaryTag(Weather)({
  Sun: /^(Italy|Spain)$/,
  Rain: "UK",
})

The overlap behaviour is unspecified. We should have it follow input order similar to the codecs implemented with foldToUnion (i.e. t.union).

How would this handle encoding?