formik icon indicating copy to clipboard operation
formik copied to clipboard

TypeScript type shorthands for setFieldValue and setFieldTouched

Open mathieucaroff opened this issue 2 years ago • 2 comments

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.

mathieucaroff avatar Mar 16 '23 15:03 mathieucaroff

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.

pachuka avatar Apr 18 '23 15:04 pachuka

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

samirant15 avatar Feb 28 '24 16:02 samirant15