Formik: Why FieldProps field.name prop is string type?

Created on 31 Jan 2018  路  3Comments  路  Source: formium/formik

Bug, Feature, or Question?

Question

Current Behavior

In this example when I try to access to access to touched[name] or errors[name], but I get this error

[ts] Element implicitly has an 'any' type because type 'FormikTouched<FormValues>' has no index signature.
interface FormValues {
  email: string;
}

const InnerForm = (props: & FormikProps<FormValues>) => {
  const { touched, errors, isSubmitting } = props;
  return (
    <Form>
      <Field 
        type="email"
        name="email" 
        render={(props: FieldProps<FormValues>)=> {
          const { name } = props.field;
          const { touched, errors } = props.form; 

          return (
            <div>
              <input type="email" name={name} />
              {touched[name] && errors[name] && errors[name]}
            <div/>
          );
        }}
      />
      {touched.email && errors.email && <div>{errors.email}</div>}

      <button type="submit" disabled={isSubmitting}>
        Submit
      </button>
    </Form>
  );
};

If I change the type of field.name on FieldProps to keyof V. The previous error is fixed.

export interface FieldProps<V = any> {
    field: {
        // ...
        name: keyof V;
    };
    form: FormikProps<V>;
}

My questions are, does exist a better way to access to touched[name] or errors[name] without the explicit use .email? and why a field.name should be different to a value defined on FormValues ?

Desired Behavior

...

Suggested Solutions

Maybe change the type of field.name on FieldProps to keyof V

Info

  • Formik Version: 0.10.5
  • OS: OSX high Sierra
  • Node Version: v8.9.4
  • TypeScript Version: v2.6.2
  • Package Manager and version: Yarn 1.3.2
TypeScript Medium Bug

Most helpful comment

@NicholasLYang you should be able to use either touched[name as keyof typeof touched] or getIn(touched, name). I believe getIn, a helper function formik uses in these scenarios, is exported.

All 3 comments

name could be a string now as it could be a dot path to a nested part of state (e.g. name="social.facebook". I think we need to write an overload.

I'm running into this issue right now. Is there a recommended fix? I tried asserting that touched[name] is a boolean, but TypeScript doesn't seem to accept that.

Thanks!

@NicholasLYang you should be able to use either touched[name as keyof typeof touched] or getIn(touched, name). I believe getIn, a helper function formik uses in these scenarios, is exported.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

Jucesr picture Jucesr  路  3Comments

jaredpalmer picture jaredpalmer  路  3Comments

ancashoria picture ancashoria  路  3Comments

najisawas picture najisawas  路  3Comments

jeffbski picture jeffbski  路  3Comments