Effect CommunityEC
Effect Community2y ago
6 replies
Stephen Bluck

Pattern Matching Discriminated Union

Are there any ways to pattern match a discriminated union with a single member with a _tag constraint?
E.g.
type ActionError<E extends { _tag: string }> = E | Redirect | NotFound | Unauthorized | Unexpected

const match = <E extends { _tag: string }>(e: ActionError<E>) =>
  Effect.gen(function* () {
    const headers = yield* ResponseHeaders;

    const result = Match.value(e).pipe(
      // Type errors
      Match.tags({
        NotFound: () => Effect.failSync(() => json(null, { status: 404, headers })),
        Unauthorized: () => Effect.failSync(() => json(null, { status: 401, headers })),
        Redirect: (e) => Effect.failSync(() => redirect(e.location, { headers })),
        Unexpected: (e) => Effect.failSync(() => json({ error: e.error }, { status: 500, headers })),
      }),
      Match.orElse((e) => Effect.succeed<E>(e)),
    );
  });
Was this page helpful?