jaredpalmer / formik

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

TypeScript type shorthands for setFieldValue and setFieldTouched #3742

Open mathieucaroff opened 1 year ago

mathieucaroff commented 1 year ago

Feature request

Current Behavior

Currently, the types of setFieldValue, setFieldError and setFieldTouched are the following:

export interface FormikHelpers<Values> {
  setFieldValue: (field: string, value: any, shouldValidate?: boolean) => void
  setFieldError: (field: string, message: string | undefined) => void
  setFieldTouched: (field: string, isTouched?: boolean, shouldValidate?: boolean) => void
  // ...
}

Desired Behavior

In TypeScript, I'd like to be able to pass the setFieldValue and setFieldTouched functions as parameter of other functions without having to write such lengthy types.

Suggested Solution

Introduce a dedicated type for these three functions. I'm not sure what naming would be best, but here's my best attempt:

export type SetFieldValue<ValueType = any> = (field: string, value: ValueType, shouldValidate?: boolean) => void
export type SetFieldError = (field: string, message: string | undefined) => void
export type SetFieldTouched = (field: string, isTouched?: boolean, shouldValidate?: boolean) => void

Who does this impact? Who is this for?

This will make typing easier for TypeScript users.

Alternatives

Until this feature is adopted, Formik TypeScript users can have their own type definition somewhere in their codebase for these three functions.

pachuka commented 1 year ago

Another alternative is to just reference the internal type:

type SetFieldError = FormikHelpers<REPLACEME>['setFieldError'];

This results in: image

You can use FormikHelpers<REPLACEME>['setFieldError'] directly rather than creating any custom types.

samirant15 commented 5 months ago

I implemented a small function as a solution for this issue, take a look here: https://github.com/jaredpalmer/formik/issues/1388#issuecomment-1969302106