Hyperlinkv0.8.0-beta.28

Schema

Schema.flipfunctioneffect/Schema.ts:2566
flip<S>

Swaps the decoded and encoded sides of a schema.

When to use

Use to invert a schema transformation direction.

Details

Calling flip twice returns the original schema.

Example (Flipping a number-from-string schema)

import { Schema } from "effect"

// NumberFromString: decodes string → number
const flipped = Schema.flip(Schema.NumberFromString)
// flipped: decodes number → string
transforming
Source effect/Schema.ts:256658 lines
export interface flip<S extends Top> extends
  BottomLazy<
    SchemaAST.AST,
    flip<S>,
    ReadonlyArray<Constraint>,
    S["~encoded.mutability"],
    S["~encoded.optionality"],
    ConstructorDefault,
    S["~type.mutability"],
    S["~type.optionality"]
  >
{
  readonly "Type": S["Encoded"]
  readonly "Encoded": S["Type"]
  readonly "DecodingServices": S["EncodingServices"]
  readonly "EncodingServices": S["DecodingServices"]
  readonly "~type.make.in": S["Encoded"]
  readonly "~type.make": S["Encoded"]
  readonly "Iso": S["Encoded"]
  readonly [FlipTypeId]: typeof FlipTypeId
  readonly schema: S
}

function isFlip$(schema: Top): schema is flip<any> {
  return Predicate.hasProperty(schema, FlipTypeId) && schema[FlipTypeId] === FlipTypeId
}

/**
 * Swaps the decoded and encoded sides of a schema.
 *
 * **When to use**
 *
 * Use to invert a schema transformation direction.
 *
 * **Details**
 *
 * Calling `flip` twice returns the original schema.
 *
 * **Example** (Flipping a number-from-string schema)
 *
 * ```ts
 * import { Schema } from "effect"
 *
 * // NumberFromString: decodes string → number
 * const flipped = Schema.flip(Schema.NumberFromString)
 * // flipped: decodes number → string
 * ```
 *
 * @category transforming
 * @since 4.0.0
 */
export function flip<S extends Top>(schema: S): S extends flip<infer F> ? F["Rebuild"] : flip<S>
export function flip<S extends Top>(schema: S): flip<S> {
  if (isFlip$(schema)) {
    return schema.schema.rebuild(SchemaAST.flip(schema.ast))
  }
  return make(SchemaAST.flip(schema.ast), { [FlipTypeId]: FlipTypeId, schema })
}
Referenced by 1 symbols