Hyperlinkv0.8.0-beta.28

SchemaGetter

SchemaGetter.withDefaultfunctioneffect/SchemaGetter.ts:638
<T, R = never>(
  defaultValue: Effect.Effect<T, SchemaIssue.Issue, R>
): Getter<T, T | undefined, R>

Creates a getter that replaces undefined values with a default.

When to use

Use when you need a schema getter to provide a fallback for a field that may be undefined in the encoded input.

Details

  • If the input is Some(undefined) or None, produces Some(T).
  • If the input is Some(value) where value is not undefined, passes it through.
  • defaultValue is an Effect that will be executed each time a default is needed.

Example (Providing a default value for an optional field)

import { Effect, SchemaGetter } from "effect"

const withZero = SchemaGetter.withDefault(Effect.succeed(0))
// Getter<number, number | undefined>
constructorsonNonerequired
export function withDefault<T, R = never>(
  defaultValue: Effect.Effect<T, SchemaIssue.Issue, R>
): Getter<T, T | undefined, R> {
  return new Getter((o) => {
    const filtered = Option.filter(o, Predicate.isNotUndefined)
    return Option.isSome(filtered) ? Effect.succeed(filtered) : Effect.mapEager(defaultValue, Option.some)
  })
}
Referenced by 2 symbols