react-final-form <Field /> with TypeScript

223 Views Asked by At

I'm trying to get my head around react-final-form <Field /> with TypeScript.

Suppose I have following code:

<Field<{ foo1: string }, HTMLElement, { foo: string }>
  name="firstName"
  component={CustomInput}
  placeholder="First Name"
/>

With the definition of FieldRenderProps as:

interface FieldRenderProps<FieldValue, T extends HTMLElement = HTMLElement, InputValue = FieldValue>

My understanding is that InputValue specifies the input.value-type.

So for above field, correctly initializing initialValues in the ` would be:

<Form
  onSubmit={onSubmit}
  initialValues={{ firstName: { foo: "foo" } }}
  render={({ handleSubmit, form, submitting, pristine, values }) => (
    <form onSubmit={handleSubmit}>
      <div>
        <label>First Name</label>
        <Field<{ foo1: string }, HTMLElement, { foo: string }>
          name="firstName"
          component={CustomInput}
          placeholder="First Name"
        />
      </div>
    </form>
  )}
/>

Unfortunately, there's nothing that stops me from initializing it with missmatching type:

<Form
  onSubmit={onSubmit}
  // below code does not match Field-type, but still no error here
  initialValues={{ firstName: "foo" }}
  render={({ handleSubmit, form, submitting, pristine, values }) => (
    <form onSubmit={handleSubmit}>
      <div>
        <label>First Name</label>
        <Field<{ foo1: string }, HTMLElement, { foo: string }>
          name="firstName"
          component={CustomInput}
          placeholder="First Name"
        />
      </div>
    </form>
  )}
/>

So my first question is: what do we need to do to ensure type-safety?

And my second question is related to the first. If we go inside of the CustomInput-component and destructure input from props, we can access the input.onChange-callback. However, it accepts events of any-type, which kind of does not make sense to me. If it's clear that input.value needs to be of type { foo: string }, why whould input.onChange accept an event of any-type? Is there a smart way of improving input.onChange's type-safety?

enter image description here

Last question that I have is about the purpose of FieldValue of FieldRenderProps. What does it actually do?

Here's a codesandbox with the above example.

0

There are 0 best solutions below