1
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.

1
  • Note that checking for undefined specifically does not rule out all "empty" scenarios - it could also be null or other similar falsy value that you might not necessarily want to render. Commented Jul 19, 2021 at 17:15

1 Answer 1

3

Checking the type of a nested property doesn't narrow its type, unfortunately. You can fix it by extracting the value into a standalone variable first (which also helps make the code more DRY):

const fieldErrors = formik.errors[fieldName];
let errors = fieldErrors === undefined ? '' : fieldErrors;
errors += status === undefined ? '' : status;
return errors;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.