Hyperlinkv0.8.0-beta.28

SchemaTransformation

SchemaTransformation.optionFromNullishOrfunctioneffect/SchemaTransformation.ts:1243
<T>(options?: { onNoneEncoding: null | undefined }): Transformation<
  Option.Option<T>,
  T | null | undefined
>

Decodes T | null | undefined into Option<T> and encodes Option<T> back to T | null or T | undefined depending on the provided options.onNoneEncoding (defaults to undefined).

When to use

Use when you need a schema transformation to convert nullish API fields to Option when both null and undefined represent absence.

Details

Decoding maps null and undefined to Option.none() and all other values to Option.some(value). Encoding maps Option.none() to null or undefined according to options.onNoneEncoding, and maps Option.some(value) to value. The transformation is pure and synchronous.

Example (Converting nullish values to an Option and encoding None as null)

import { Schema, SchemaTransformation } from "effect"

const schema = Schema.NullishOr(Schema.String).pipe(
  Schema.decodeTo(
    Schema.Option(Schema.String),
    SchemaTransformation.optionFromNullishOr({ onNoneEncoding: null })
  )
)
export function optionFromNullishOr<T>(
  options?: {
    onNoneEncoding: null | undefined
  }
): Transformation<Option.Option<T>, T | null | undefined> {
  return transform({
    decode: Option.fromNullishOr,
    encode: options?.onNoneEncoding === null ? Option.getOrNull : Option.getOrUndefined
  })
}
Referenced by 1 symbols