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;
// A comment indicates the issue. The errors variable being of type: string | undefined. Does typescript account for ternary operators or is there something I'm not seeing?
let errors = formik.errors[fieldName] === undefined ? '' : formik.errors[fieldName];
errors += status === undefined ? '' : status;
return errors;
}
return [showErrors, getErrors]
};
The dilemma is highlighted in a comment within the code snippet. The errors variable is declared as string | undefined
. How does TypeScript handle ternary operators in such cases? Any insights would be greatly appreciated.