TanStackT
TanStack7mo ago
16 replies
living-lavender

Type error in createServerValidate when using discriminated union schemas

When using discriminated unions as schemas, the createServerValidate function gives a type error. If I cast the defaultValues in formOptions, the error goes away. Is this the intended approach or is there some more type safe way to use discriminated unions?

Stackblitz: https://stackblitz.com/edit/tanstack-form-tnj3qpfd?file=src%2Findex.tsx

import { createServerValidate, formOptions } from '@tanstack/react-form/remix';
import { z } from 'zod';

const UnionFoo = z.object({ discriminator: z.literal('foo'), foo: z.string() });

const UnionBar = z.object({ discriminator: z.literal('bar') });

const ExampleSchema = z.discriminatedUnion('discriminator', [
  UnionFoo,
  UnionBar,
]);

const formDefaultValues: z.input<typeof ExampleSchema> = {
  discriminator: 'foo',
  foo: 'example',
};

const formOpts = formOptions({
  /* Works with the casting below. Is this the preferred way? */
  defaultValues: formDefaultValues /* as z.input<typeof ExampleSchema> */,
  validators: {
    onChange: ExampleSchema,
  },
});

// Type error
const serverValidate = createServerValidate({
  ...formOpts,
  onServerValidate: (values) => {
    console.log(values);
  },
});
StackBlitz
Run official live example code for Form Simple, created by Tanstack on StackBlitz
Form Simple Example (duplicated) - StackBlitz
Was this page helpful?