Hyperlinkv0.8.0-beta.28

Schema

Schema.ArrayEnsurefunctioneffect/Schema.ts:4592
ArrayEnsure<S>

Creates a schema that accepts either a value decoded by schema or an array decoded by Schema.Array(schema), then returns an array.

When to use

Use to accept input that may be provided either as one item or as an array, while normalizing decoded values to a readonly array.

Details

During encoding, one-element arrays are encoded as the single element. Empty arrays and arrays with two or more elements are encoded as arrays.

Gotchas

The single-value branch is tried before the array branch. If schema itself accepts arrays, an array input can be treated as one value and wrapped in a one-element array.

constructorsArrayNonEmptyArray
Source effect/Schema.ts:459239 lines
export interface ArrayEnsure<S extends Constraint> extends decodeTo<$Array<toType<S>>, Union<readonly [S, $Array<S>]>> {
  readonly "Rebuild": ArrayEnsure<S>
}

/**
 * Creates a schema that accepts either a value decoded by `schema` or an array
 * decoded by `Schema.Array(schema)`, then returns an array.
 *
 * **When to use**
 *
 * Use to accept input that may be provided either as one item or as an array,
 * while normalizing decoded values to a readonly array.
 *
 * **Details**
 *
 * During encoding, one-element arrays are encoded as the single element. Empty
 * arrays and arrays with two or more elements are encoded as arrays.
 *
 * **Gotchas**
 *
 * The single-value branch is tried before the array branch. If `schema` itself
 * accepts arrays, an array input can be treated as one value and wrapped in a
 * one-element array.
 *
 * @see {@link Array} for accepting only array input
 * @see {@link NonEmptyArray} for requiring at least one decoded element
 *
 * @category constructors
 * @since 3.10.0
 */
export function ArrayEnsure<S extends Constraint>(schema: S): ArrayEnsure<S> {
  return Union([schema, ArraySchema(schema)]).pipe(decodeTo(
    ArraySchema(toType(schema)),
    SchemaTransformation.transform({
      decode: Arr.ensure,
      encode: (array) => array.length === 1 ? array[0] : array
    })
  ))
}