Hyperlinkv0.8.0-beta.28

Schema

Schema.withConstructorDefaultfunctioneffect/Schema.ts:5646
withConstructorDefault<S>

Attaches a constructor default value to a schema field.

Details

Constructor defaults are applied only during make*, not during decoding or encoding.

Example (Defining an optional field with a static default)

import { Effect, Schema } from "effect"

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

const value = MySchema.make({})
// value: { name: "anonymous" }
constructors
Source effect/Schema.ts:564657 lines
export interface withConstructorDefault<S extends Constraint & WithoutConstructorDefault> extends
  BottomLazy<
    S["ast"],
    withConstructorDefault<S>,
    S["~type.parameters"],
    S["~type.mutability"],
    S["~type.optionality"],
    "with-default",
    S["~encoded.mutability"],
    S["~encoded.optionality"]
  >
{
  readonly "Type": S["Type"]
  readonly "Encoded": S["Encoded"]
  readonly "DecodingServices": S["DecodingServices"]
  readonly "EncodingServices": S["EncodingServices"]
  readonly "~type.make.in": S["~type.make.in"]
  readonly "~type.make": S["~type.make"]
  readonly "Iso": S["Iso"]
  readonly schema: S
}

/**
 * Attaches a constructor default value to a schema field.
 *
 * **Details**
 *
 * Constructor defaults are applied only during `make*`, not during decoding or
 * encoding.
 *
 * **Example** (Defining an optional field with a static default)
 *
 * ```ts
 * import { Effect, Schema } from "effect"
 *
 * const MySchema = Schema.Struct({
 *   name: Schema.String.pipe(
 *     Schema.optionalKey,
 *     Schema.withConstructorDefault(Effect.succeed("anonymous"))
 *   )
 * })
 *
 * const value = MySchema.make({})
 * // value: { name: "anonymous" }
 * ```
 *
 * @category constructors
 * @since 3.10.0
 */
export function withConstructorDefault<S extends Constraint & WithoutConstructorDefault>(
  // `S["~type.make.in"]` instead of `S["Type"]` is intentional here because
  // it makes easier to define the default value if there are nested defaults
  defaultValue: Effect.Effect<S["~type.make.in"], SchemaError>
) {
  return (schema: S): withConstructorDefault<S> =>
    make(SchemaAST.withConstructorDefault(schema.ast, toIssueEffect(defaultValue)), { schema })
}
Referenced by 1 symbols