Effect CommunityEC
Effect Community2y ago
6 replies
nemmind1

Schema vs Simplify issue

The server response contains an ok flag to indicate is it a fixed error type or a custom schema response
I want to get an Either as output without the ok prop (and without casting to any)

import { Struct } from 'effect'
import { Schema } from '@effect/schema'

const createApiResponseSchema = <FROM, TO, R>(
  resultSchema: Schema.Schema<FROM, TO, R>,
) =>
  Schema.EitherFromUnion({
    left: Schema.Struct({
      ok: Schema.Literal(false),
      error: Schema.String,
    }).pipe(Schema.transform(Schema.String, {
      decode: (response) => response.error, // I only care about the error prop
      encode: (error) => ({
        ok: false as const,
        error,
      }),
    })),
    right: Schema.extend( // I do not want to define ok in every custom response schema
      Schema.Struct({ // so I extend it here
        ok: Schema.Literal(true),
      }),
      resultSchema,
    ).pipe(
      Schema.transform(resultSchema, { // ok prop always true here, does not have meaning
        decode: (fromA) => { // so it should be removed, but
          fromA.ok // This cause a compile error:
          // "Property 'ok' does not exist on type 'Simplify<FROM & { readonly ok: true; }>'"
          // But I know there is an ok prop here

          const shouldBeReturned = Struct.omit('ok')(fromA); // also compile error here

          throw new Error('Function not implemented.')
        },
        encode: (result) => ({
          ok: true as const,
          ...result
        }),
      }),
    ),
  })


Is it a bug? Can somebody help?
Was this page helpful?