pattern-matching-ts icon indicating copy to clipboard operation
pattern-matching-ts copied to clipboard

[feature] `matchSum`

Open waynevanson opened this issue 3 years ago • 2 comments

Sometimes the name of the tag can be used as the lookup value in the struct. It's similar to fromSum in io-ts/Encoder.

It basically looks up the value from the sum identifier.

These types don't assume a default case currently.

declare function matchSum<S extends string>(
  sum: S,
): <
  A extends Record<S, string>,
  M extends {
    [P in A[S]]: (
      value: Extract<A, Record<S, P> & Record<P, unknown>>[P],
    ) => unknown
  },
>(
  matcher: M,
) => (fa: A) => ReturnType<M[keyof M]>

declare const sumType:
  | { _tag: "aside"; aside: string }
  | { _tag: "bside"; bside: number }

// boolean | null
const sum = pipe(
  sumType,
  matchSum("_tag")({
    aside: (string) => true,
    bside: (number) => null,
  }),
)

What are your thoughts on this, happy to accept this?

waynevanson avatar Oct 03 '21 04:10 waynevanson

We can also derive some functions using these examples: https://serde.rs/enum-representations.html

waynevanson avatar Apr 10 '23 01:04 waynevanson

We can also derive some functions using these examples: https://serde.rs/enum-representations.html

Hey, @waynevanson thanks a lot for the effort and the interest you showed in this! Really appreciated! 🙏

Sadly I don't have time to follow this project at the moment 😞

If you want to open a draft PR you are more than welcome but before starting I wanted you to know that I've no idea when I will be able to review it

stefano-regosa-deel avatar Apr 12 '23 17:04 stefano-regosa-deel