Hyperlinkv0.8.0-beta.28

SchemaTransformation

SchemaTransformation.optionFromOptionalfunctioneffect/SchemaTransformation.ts:1337
<T>(): Transformation<Option.Option<T>, T | undefined>

Decodes optional values into Option<T> and encodes Option.none() back to an omitted optional value.

When to use

Use when you need a schema transformation to convert optional (possibly undefined) values to Option.

Details

Decoding maps an absent or undefined value to Some(None) and a present value to Some(Some(v)). Encoding maps Some(None) to None to omit the value, and maps Some(Some(v)) to Some(v). This uses transformOptional under the hood and filters out undefined on decode.

Example (Converting an optional value to an Option)

import { Schema, SchemaTransformation } from "effect"

const schema = Schema.Struct({
  age: Schema.optional(Schema.Number).pipe(
    Schema.decodeTo(
      Schema.Option(Schema.Number),
      SchemaTransformation.optionFromOptional()
    )
  )
})
export function optionFromOptional<T>(): Transformation<Option.Option<T>, T | undefined> {
  return transformOptional<Option.Option<T>, T | undefined>({
    decode: (ot) => ot.pipe(Option.filter(Predicate.isNotUndefined), Option.some),
    encode: Option.flatten
  })
}
Referenced by 1 symbols