Hyperlinkv0.8.0-beta.28

Schema

Schema.withDecodingDefaultfunctioneffect/Schema.ts:5837
withDecodingDefault<S, R>

Wraps the Encoded side with optional (key absent or undefined) and provides a default Encoded value when the field is missing or undefined during decoding.

When to use

Use when the default is expressed in the encoded representation, before the field's decoding transformation runs.

Details

The default value is specified in terms of the Encoded type (before any decoding transformations).

Options:

  • encodingStrategy:
    • "passthrough" (default): include the value in the encoded output.
    • "omit": omit the key from the encoded output.

Example (Providing a default for an optional field value)

import { Effect, Schema } from "effect"

const MySchema = Schema.Struct({
  name: Schema.String.pipe(Schema.optional, Schema.withDecodingDefault(Effect.succeed("anonymous")))
})

const result = Schema.decodeUnknownSync(MySchema)({ name: undefined })
// result: { name: "anonymous" }
Source effect/Schema.ts:583755 lines
export interface withDecodingDefault<S extends Constraint, R = never> extends decodeTo<S, optional<toEncoded<S>>, R> {
  readonly "Rebuild": withDecodingDefault<S, R>
}

/**
 * Wraps the `Encoded` side with `optional` (key absent **or** `undefined`)
 * and provides a default `Encoded` value when the field is missing or
 * `undefined` during decoding.
 *
 * **When to use**
 *
 * Use when the default is expressed in the encoded representation, before the
 * field's decoding transformation runs.
 *
 * **Details**
 *
 * The default value is specified in terms of the `Encoded` type (before any
 * decoding transformations).
 *
 * Options:
 *
 * - `encodingStrategy`:
 *   - `"passthrough"` (default): include the value in the encoded output.
 *   - `"omit"`: omit the key from the encoded output.
 *
 * **Example** (Providing a default for an optional field value)
 *
 * ```ts
 * import { Effect, Schema } from "effect"
 *
 * const MySchema = Schema.Struct({
 *   name: Schema.String.pipe(Schema.optional, Schema.withDecodingDefault(Effect.succeed("anonymous")))
 * })
 *
 * const result = Schema.decodeUnknownSync(MySchema)({ name: undefined })
 * // result: { name: "anonymous" }
 * ```
 *
 * @see {@link withDecodingDefaultKey} for the key-level variant (key absent only, not `undefined`)
 * @see {@link withDecodingDefaultType} for the variant where the default is a `Type` value
 * @category decoding
 * @since 3.10.0
 */
export function withDecodingDefault<S extends Constraint, R = never>(
  defaultValue: Effect.Effect<S["Encoded"], SchemaError, R>,
  options?: DecodingDefaultOptions
) {
  const encode = options?.encodingStrategy === "omit" ? SchemaGetter.omit() : SchemaGetter.passthrough()
  return (self: S): withDecodingDefault<S, R> => {
    return optional(toEncoded(self)).pipe(decodeTo(self, {
      decode: SchemaGetter.withDefault(toIssueEffect(defaultValue)),
      encode
    }))
  }
}
Referenced by 1 symbols