arktypea
arktype6mo ago
mikolaj

Matching on custom types

I have an array of errors (typed as any[]) that I need to transform. I’d like to break the transformation into several match cases. I’ve already done this with the Fluent API, but I’m not sure if the same approach works with the string-based API.

const FieldError = ({ title }: FieldErrorProps) => {
  const field = useFieldContext();
  const errors = field.state.meta.errors.flatMap((error: unknown) => {
    const parser = match
      .case(type.instanceOf(ArkErrors), (e) =>
        e.flatMap((arkError) =>
          arkError.hasCode('intersection')
            ? arkError.errors.map((arkErrorError) => arkErrorError.message)
            : [arkError.message]
        )
      )
      .case(type.instanceOf(ArkError), (e) =>
        e.hasCode('intersection')
          ? e.errors.map((arkErrorError) => arkErrorError.message)
          : [e.message]
      )
      .case("Error", (e) => [e.message])
      .default((e) => [e?.toString() ?? 'Unknown error']);
    return parser(error);
  });
  return <ErrorAlert title={title} errors={errors} />;
};


P.S.
  1. I'd appreciate any guidence if there is a better solution than a match here or if i could make field.state.meta.errors in Tanstack Form more type-safe when using the useFieldContext. Probably what I should do instead is just transform the errors into strings at the form level and pass it to a pure component.
  2. Thanks for this library! It's one of greatest things I've came across on my recent journey into the TypeScript land.
Was this page helpful?