Skip to content
This repository has been archived by the owner on Jul 16, 2024. It is now read-only.

fallback

Giulio Canti edited this page Jun 13, 2023 · 2 revisions

@effect/schema version: v0.20.1

import * as S from '@effect/schema/Schema'
import * as E from '@effect/data/Either'

const DeckType = S.literal('orange', 'red', 'green', 'purple', 'blue')

const fallback = <I, A extends I, B>(
  from: S.Schema<I, I>,
  schema: S.Schema<A, B>,
  value: B
): S.Schema<I, B> =>
  S.transformResult(
    from,
    S.to(schema),
    (i) => E.orElse(S.parseEither(schema)(i), () => E.right(value)),
    S.encodeEither(schema)
  )

const DeckTypeFallback = fallback(S.string, DeckType, 'red')

console.log(S.parse(DeckTypeFallback)('orange')) // 'orange'
console.log(S.parse(DeckTypeFallback)('wrong')) // 'red'
Clone this wiki locally