I'm currently working with Formik, which includes this particular type:
type FormikErrors<Values> = {
[K in keyof Values]?: Values[K] extends object
? FormikErrors<Values[K]>
: string
};
In addition to this type, there is a validation function that resembles
validate<Values>(v: Values) => FormikErrors<Values>
. The main concept here is that the keys of FormikErrors align with the keys of Values and correspond to either a string error message or a recursive FormikErrors object if the field is represented by a nested object.
My objective is to create a generic function for validating required fields. This function specifically targets flat Values.
export function validateRequired<T, K extends keyof T>(values : T, names: K[]) : FormikErrors<T> {
let errors : FormikErrors<T> = {};
names.forEach((name) => {
if (!values[name]) {
errors[name] = 'This field is required';
}
});
return errors;
}
An issue arises with this setup:
Type error: Type '"This field is required"' is not assignable to type '(T[K] extends object ? FormikErrors<T[K]> : string) | undefined'. TS2322
This error occurs because the values returned by validateRequired are always strings and never nested FormikValues. Is there a method to indicate that the values will consistently be scalars so that this can pass the type checking?