Type Error with `optionalToRequired` and Custom Decoding Logic

Am I misusing optionalToRequired here? I have a type error but the type inference and runtime behaviour are OK.

I am trying to decode { parent?: number } to { parent: number | null }.

Since null is not a subtype of
number
I can't use withDecodingDefault.

import { Effect, Option, Schema as S, pipe } from "effect"

const OptionalToNullable = <T>(schema: S.Schema<T>) =>
  S.optionalToRequired(
    // @ts-ignore
    schema,
    S.NullOr(schema),
    {
      encode: (a) => Option.some(a),
      decode: (a) => Option.isNone(a) ? null : a.value
    }
  )

const Node = S.Struct({
  id: S.Number,
  parent: OptionalToNullable(S.Number)
})

const program = pipe(
  S.decodeUnknown(Node)({ id: 2 }),
  Effect.tap(Effect.log) // { id: 2, parent: null }
)
Was this page helpful?