interface FormikInstance {
touched: {[key: string]: boolean | undefined}
errors: {[key: string]: string | undefined}
status?: {[key: string]: string}
}
const useFormikErrors = (formik: FormikInstance) => {
const showErrors = (fieldName: string): boolean => {
const status = formik.status ? formik.status[fieldName] : undefined;
return !!formik.touched[fieldName] && (!!formik.errors[fieldName] || !!status);
}
const getErrors = (fieldName: string): string => {
const status = formik.status ? formik.status[fieldName] : undefined;
// errors is of type: string | undefined, but should be string
let errors = formik.errors[fieldName] === undefined ? '' : formik.errors[fieldName];
errors += status === undefined ? '' : status;
return errors;
}
return [showErrors, getErrors]
};
The problem is marked in a comment. The errors variable is string | undefined. Does typescript consider ternary operators, or am I missing something obvious here?
Thanks in advance.
undefinedspecifically does not rule out all "empty" scenarios - it could also benullor other similar falsy value that you might not necessarily want to render.