jaredpalmer / formik

Build forms in React, without the tears 😭
https://formik.org
Apache License 2.0
34k stars 2.79k forks source link

<Formik /> has loose prop types #3170

Open munizart opened 3 years ago

munizart commented 3 years ago

Bug report

Current Behavior

<Formik /> accepts any prop, this make it impossible for TS compiler to find typos on props name.

Expected behavior

IMHO, unexpected props should not be acceptable by default, but rather require explicit type

Reproducible example

return (<Formik
  initialValues={myInitialValue}
  validationScheme={myValidationSchema} // fails to spot the typo.
  onSubmit={onSubmit}
>)

Suggested solution(s)

Currently, passing Formik explicit type parameters works around this behavior.

return (<Formik<MyValueType>
  initialValues={myInitialValue}
  validationScheme={myValidationSchema} // Object literal may only specify known properties, but 'validationScheme' does not exist in type 'FormikConfig<MyValueType>'. Did you mean to write 'validationSchema'?
  onSubmit={onSubmit}
>)

This works because it bypass type inference for type parameters and the compiler was inferring the ExtraProps with validationScheme on it. To solve this it's needed to somehow disable inference for ExtraProps. The way i find to work is to change:

export declare function Formik<Values extends FormikValues = FormikValues, ExtraProps = {}>(props: FormikConfig<Values> & ExtraProps): JSX.Element;

to

type NoInfer<T> = [T][T extends any ? 0 : never];
export declare function Formik<Values extends FormikValues = FormikValues, ExtraProps = {}>(props: FormikConfig<Values> & NoInfer<ExtraProps>): JSX.Element;

Additional context

Affects only typescript users

Your environment

Software Version(s)
Formik 2.1.5
React 16.13.0
TypeScript 4.2.3
npm/Yarn 1.22.10
munizart commented 3 years ago

Update: I've created this draft PR (#3177) so the proposed solution can be tested more easily.

johnrom commented 3 years ago

The NoInfer type was sourced from here and has some known issues. I think we might want to wait for an official recommended NoInfer type.

I personally never use the ExtraProps here, so I may underestimate how large of a problem this is. If it's not a major problem and can be worked around by triple checking for typos, we should probably wait for an official solution.

github-actions[bot] commented 3 years ago

This issue is stale because it has been open 30 days with no activity. Remove stale label or comment or this will be closed in 60 days

github-actions[bot] commented 3 years ago

This issue is stale because it has been open 30 days with no activity. Remove stale label or comment or this will be closed in 60 days

github-actions[bot] commented 3 years ago

This issue is stale because it has been open 30 days with no activity. Remove stale label or comment or this will be closed in 60 days