Skip to content

Match multiple union types #2

@janwirth

Description

@janwirth

twop/ts-union provides the experimental matchWith syntax: https://github.com/twop/ts-union#experimental-matchwith

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 = (prev: typeof State.T, ev: typeof Ev.T) =>
  State.match(prev, {
    Loading: () =>
      Ev.match(ev, {
        ErrorHappened: (err) => Err(err),
        DataFetched: (data) => Loaded(data),
      }),

    Loaded: (loadedData) =>
      // just add to the current loaded value as an example
      Ev.if.DataFetched(
        ev,
        (data) => Loaded(loadedData + data),
        () => prev
      ),

    default: (s) => s,
  });

Are ther any plans to support this?
Maybe the following syntax could work:

matchExhaustive(dataAorB, {
   a: matchWith(dataCorD, {
      // matchWith puts the args to the constructors in an array
      c: ([[aPayload, aPayload2nd], [cPayload]]) => cPayload && aPaylod2,
      d: () => false
   }
   b: (arg) => true // or wildcard
})

This is probably very tricky to type, isn't it?

Metadata

Metadata

Assignees

Labels

enhancementNew feature or request

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions