formik
formik copied to clipboard
TypeScript type shorthands for setFieldValue and setFieldTouched
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.
Another alternative is to just reference the internal type:
type SetFieldError = FormikHelpers<REPLACEME>['setFieldError'];
This results in:

You can use FormikHelpers<REPLACEME>['setFieldError'] directly rather than creating any custom types.
I implemented a small function as a solution for this issue, take a look here: https://github.com/jaredpalmer/formik/issues/1388#issuecomment-1969302106