Composing schemas with an optional transformation in a way similar to `Option.map` can be achieve...

Is there a way to compose schemas with an option in an "Option.map" like fashion?

What I mean is this:

const MaybeString = S.OptionFromNonEmptyTrimmedString
export const CsvDate = S.transformOrFail(S.NonEmptyString, S.DateFromSelf, {
  strict: true,
  decode: (i, _, ast) => {
    const parsed = parse(i, "dd. LLL yyyy", new Date(), { locale: de });
    if (isValid(parsed)) {
      return ParseResult.succeed(parsed);
    } else {
      return ParseResult.fail(new ParseResult.Type(ast, i, "Ungültiges Datum"));
    }
  },
  encode: (a) =>
    ParseResult.succeed(formatInTimeZone(a, "Europe/Berlin", "dd. LLL yyyy", { locale: de })),
});

const X = MaybeString.pipe(S.compose(CsvDate);
const decode = S.decodeUnknownSync(X)
expect(decode("")).toStrictEqual(Option.none())
expect(decode("31. Dec 2024").toStrictEqual(Option.some(new Date("31. Dec 2024")));
Was this page helpful?