iway1 / react-ts-form

https://react-ts-form.com
MIT License
2.01k stars 33 forks source link

Typesafe props not working for field that is nullable.optional or .nullish #110

Closed iffa closed 1 year ago

iffa commented 1 year ago

Prop types seems to break when optional/nullable/nullish are not in the correct order. See the reprodcution below

TL;DR:

import { TextInput } from "@mantine/core";
import { createTsForm, useTsController } from "@ts-react/form";
import { z } from "zod";

const TextField = ({ description }: { description?: string }) => {
  const { field, error } = useTsController<string>();

  return (
    <TextInput
      value={field.value}
      onChange={(e) => field.onChange(e.target.value)}
      label={field.name}
      placeholder={description}
      error={error?.errorMessage}
    />
  );
};

const mapping = [[z.string(), TextField]] as const;

export const Form = createTsForm(mapping);

export const MyFormComponent = () => {
  return (
    <Form
      schema={z.object({
        displayNameOptionalNullable: z.string().optional().nullable(),
        displayNameNullableOptional: z.string().nullable().optional(),
        displayNameNullish: z.string().nullish(),
      })}
      props={{
        displayNameOptionalNullable: {
          // Works, no TS errors
          description: "",
        },
        displayNameNullableOptional: {
          // Does not work, Type '{ description: string; }' is not assignable to type 'undefined'
          description: "",
        },
        displayNameNullish: {
          // Does not work, Type '{ description: string; }' is not assignable to type 'undefined'
          description: "",
        },
      }}
      onSubmit={() => {
        /* ... */
      }}
    />
  );
};
iway1 commented 1 year ago

got a fix just seeing if I can get a review on it

davevilela commented 9 months ago

I think this is still an issue on the latest version.

Screenshot 2023-09-22 at 12 34 45

davevilela commented 9 months ago

Something interesting: It happens when my field type is wrapped in createUniqueFieldSchema

scamden commented 9 months ago

Something interesting: It happens when my field type is wrapped in createUniqueFieldSchema

Ah interesting, maybe we are failing to unwrap properly when branded (which createUniqueSchema uses under the hood). Lets create a new issue for that since it's a different problem technically. (Feel free to make a PR with a failing "type" test as well. See the tests in the PR that closed this issue for reference)

j1mie commented 5 months ago

Experiencing the same issue with createUniqueFieldSchema, props and optional fields